Sum of range of rows and columns in matrix

Hi all,

I have a large matrix of 720 x 25. I want to get sum of range of rows and columns. Like, I need sum of all columns and row number 2 to 21, then leaving 22nd row, again sum of all columns and row number 23 to 42 again leaving 43rd row and then sum of 44th to 63. Means I want to add all 25 columns of every 20 rows and escape 1 row after every addition.

For this, I was trying to use FOR loop. like

sum =0
for (i=1; i<=NF; i++)
{
for (j=1; j<=20; j++ )
{ sum =sum+$i
if j=20 {print sum} 
}
}

Please, help me to solve this.

Could this help you /

awk '{if (j==0){j++;print;next}
for (i=1;i<=NF;i++) {
sum+=$i;}
j++;print $0
if (j == 21){print "SUM ----- "sum;j=0;}
}' matrixFile

Hi pravin,

Thanks for your efforts.....

The code given by you is adding up entire matrix starting from top to every 20th row.
But, I want to add only 20 rows
starting from row # 2-21 and then
sum of row # 23 - 42, then
sum of row # 44-63... and so on.....

Also I would like to print the output in 21st column of 21st row, 21st column of 42nd row 21st column of 44th row and so on....instead of inserting a new row

Thanks in advance :slight_smile:

awk '{if (j==0){j++;print;next}
for (i=1;i<=NF;i++) {
sum+=$i;
}
j++;
if (j == 21){$21=sum;j=0;sum=0}
print $0}' MatrixFile
1 Like

Thanks Pravin :slight_smile:
It worked :b: