Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Subtract 2 matrix in awk

Status
Not open for further replies.

mguha06

Technical User
Apr 20, 2006
28
US
I am trying to subtract two matrix which are large file, into one matrix. The matrix for example as follows:

Matrix 1

4 5 7 8
6 9 12 5
3 1 0 2

Matrix 2

7 9 2 0
1 3 6 2
3 5 8 1

Subtract result will be:

-3 -4 5 8
5 6 6 3
0 -4 -8 1

Any help will eb gratly appreciated.
Thanks.

 
Hi

I suppose you are still on Windows using [tt]awk95[/tt], so probably you get the input from two text files :
Code:
[navy]FNR[/navy][teal]==[/teal]NR [teal]{[/teal]
  [b]for[/b] [teal]([/teal][navy]i[/navy][teal]=[/teal][purple]1[/purple][teal];[/teal]i[teal]<=[/teal]NF[teal];[/teal]i[teal]++)[/teal] m[teal][[/teal]NR[teal],[/teal]i[teal]]=[/teal][navy]$i[/navy]
  [b]next[/b]
[teal]}[/teal]

[teal]{[/teal]
  [b]for[/b] [teal]([/teal][navy]i[/navy][teal]=[/teal][purple]1[/purple][teal];[/teal]i[teal]<=[/teal]NF[teal];[/teal]i[teal]++)[/teal] [b]printf[/b] [green][i]"%s%s"[/i][/green][teal],[/teal]m[teal][[/teal]FNR[teal],[/teal]i[teal]][/teal]-[navy]$i[/navy][teal],[/teal]i[teal]<[/teal]NF[teal]?[/teal]OFS[teal]:[/teal]ORS
[teal]}[/teal]
Code:
[blue]C:\>[/blue] awk95 matsub.awk matrix1 matrix2

Feherke.
 
A starting point:
Code:
awk '{n1=split($0,m1);getline<"Matrix2";for(i=1;i<n1;++i)printf "%d ",m1[i]-$i;printf "%d\n",m1[n1]-$(n1)}' Matrix1

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top