Date: Mon, 31 Oct 2005 13:06:16 -0800 Dale McLerran "SAS(r) Discussion" Dale McLerran Re: IML: comparing two matrices by cell values <1130788398.682324.43150@g47g2000cwa.googlegroups.com> text/plain; charset=iso-8859-1

--- "von-hippel.1@osu.edu" <von-hippel.1@OSU.EDU> wrote:

> I am calculating a matrix C from the values in matrices A and B. > > In each matrix, I use the first two columns as a kind of index. When > I > am looking at a row of C, is there a convenient way to find the rows > of > A and B that have the same index? > > Here's an example.... Suppose I have two 3-column matrices A and B, > where B has more rows than A. E.g.: > > A = > {1 1 1, > 2 2 2}; > > B = > {1 1 0, > 2 1 0, > 2 2 0}; > > I want to create a third matrix C with the same dimension as B, and > cells filled according to the following rule. > > C[i,j,1] = B[i,j,1] > C[i,j,2] = B[i,j,2] > C[i,j,3] = A[i,j,3] if A[i,j,1]=C[i,j,1] and A[i,j,2]=C[i,j,2] > = 0 otherwise. > > So > > C = > {1 1 1, > 2 1 0, > 2 2 2}; > > How would you go about doing this? > > Thanks! > Paul >

Paul,

I don't know if there is a more efficient way to accomplish what you need, but the following code does work. We have to condition on the i-th row of A and then find all rows of B where the first two columns match A[i,1] and A[i,2]. The LOC function is employed to find the rows where this condition is true.

/* First initialize C to B, then initialize column 3 of C to zero */ C = B; C[,3]=0;

/* Loop over rows of A and find rows of B that match A[i,1] */ /* and A[i,2]. For rows of B which match, set B[j,3]=A[i,3] */ nrow_A = nrow(A); do i=1 to nrow_A; j = loc(B[,1]=A[i,1] & B[,2]=A[i,2]); if nrow(j)>0 then do; C[j,3] = A[i,3]; end; end;

print C;

Note that if there are rows in A which do not have matching first two columns in B, then the index j cannot be constructed and the number of rows for the symbol j will be zero. We only set the value of C[j,3]=A[i,3] when we do find (at least) one row of B which has the same values for columns 1 and 2 as are observed for the current row of A.

HTH,

Dale

--------------------------------------- Dale McLerran Fred Hutchinson Cancer Research Center mailto: dmclerra@NO_SPAMfhcrc.org Ph: (206) 667-2926 Fax: (206) 667-5977 ---------------------------------------

__________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com

Back to: Top of message | Previous page | Main SAS-L page