0

I have a file that contains data like this:

       column1  column2 column3
  row1  a(1,1)   a(1,2)  a(1,3)
  row2  a(2,1)   a(2,2)  a(2,3)
  row3  a(3,1)   a(3,2)  a(3,3)
  row4  a(4,1)   a(4,2)  a(4,3)


       column4  column5 column6
  row1  b(1,1)   b(1,2)  b(1,3)
  row2  b(2,1)   b(2,2)  b(2,3)
  row3  b(3,1)   b(3,2)  b(3,3)
  row4  b(4,1)   b(4,2)  b(4,3)

I need to sum the elements of the array to show an output like this the output

 column1    a(1,1)+a(2,1)       a(3,1)+a(4,1)  
 column2    a(1,2)+a(2,2)       a(3,2)+a(4,2)
 column3    a(1,3)+a(2,3)       a(3,3)+a(4,3)
 column4    b(1,1)+b(2,1)       b(3,1)+b(4,1)
 column5    b(1,2)+b(2,2)       b(3,2)+b(4,2)
 column6    b(1,3)+b(2,3)       b(3,3)+b(4,3)

I though that a way to do this is to specify the position of each number and them sum , but I have no idea how to do that.

1

2 Answers 2

1

dance of the pipes

$ sed 's/row[0-9]//;/^$/d' filenums | 
  pr -2t | 
  awk 'NR==1{$1=$1; print; next} 
     !(NR%2){split($0,a); next}          
            {for(i=1;i<=NF;i++) $i+=a[i]}1' | 
  tr ' ' '\n' | 
  pr -3t

column1                 32                      72
column2                 34                      74
column3                 36                      76
column4                 32                      72
column5                 34                      74
column6                 36                      76

to compute the sums I replaced cell indices with values with this

$ tr -d 'ab(,)' < file > filenums

so a(1,1) became 11, etc.

Sign up to request clarification or add additional context in comments.

5 Comments

One question, in the example was considered two matrices, one after the other. How can I do the same with more than two matrices, what change need to be done to the script. Thanks in advance
this is probably not the best approach for that case. I would suggest using awk's record structure with setting RS= and FS='\n' and handling headers with $1 and the data rows with even/odd fields similar to what I did with NR. Perhaps you should create a new question for that.
Karakfa, I created a new question in unix.stackexchange.com/questions/286568/… see it friend
Dear Karakfa, I solve the problem and the solution is in the previous link that I send you. But now I have a question to askyou.What if the numbers are real(not only integers), what change I need to do
Doesn't matter, awk can handle it either way. I think you posted on a different channel.
1

You can create multidimensional array something like this

awk 'BEGIN{i=0}{i++;r[i][0];split($0,r[i]," ");}END{print r[1][1]+r[2][1] #do your math here}' filename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.