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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting values diagonally in a matrix file 1

Status
Not open for further replies.

mguha06

Technical User
Apr 20, 2006
28
0
0
US
I am trying to figure out, how to extract data points from a large matrix (m by n) file. I want to extract data along an inclined straight line, along any row and column of a matrix. Example below is what I want to achieve:

Matrix Example

20 21 22 290 46
7 12 18 13 12
16 15 13 9 4
175 8 9 129 47

I want to extract the values if I draw a straight line along cells (1,1) and (4,4), which would be:

20 12 13 129

similarly, if I draw a straight line between cells (3,1) and (1,3), which would be:
16 12 22

I know, you can use arrays in awk, such as myarray[1,1], myarray[2,2], myarry[3,3],myarray[4,4].

However, this might not be the right solution, as my matrix can be 1000 by 1000.

Can anyone help to write a generic awk code, where I will able to provide the first starting cells and the last starting cells and selecting all the values of the cells that lies within the straight line of the first and the last selected cells. This would help me tremendously. I am a very novice user of awk, and I was told that this could be done easily by awk.

Any help is greatly appreciated!

Thanks.





 
nawk -v s='1,2' -v e='4,4' -f mg.awk myMatrix.txt

mg.awk:
Code:
BEGIN {
  split(s,sA, ",")
  split(e,eA, ",")
}
NR>=sA[1] && NR<=eA[1] {print $(sA[2]+ c++)}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks vgersh99! However, I only use awk not nawk. Can the first part of the statement be written in awk? Thanks.
 
Try the same with 'awk'.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
I am using awk95 and I am getting an error. This is the command I am using

awk95 -f -v s='1,2' -v e='4,4' -f mg.awk myMatrix.txt
 
This is not what's been posted originally.

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
awk95 -v s='1,2' -v e='4,4' -f mg.awk myMatrix.txt
I have replaced nawk with awk95 (that's the version I am using). It runs, but with no output data.
 
I am using gawk now. It works. I think, when the starting row number is greater than the ending row number, it does not output correctly.

Anyhow, it is a great code. I am giving you all the stars that i can give.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top