RedBlueGreen
RedBlueGreen

Reputation: 23

How to match elements in 2 matrices and create a new matrix with specific values dependent on previous matrices in R?

I have two matrices, A and B both are 100*100. Both these matrices have positive and negative numbers. I want to create a matrix C with the same dimensions and the elements in this matrix are dependent on the elements at the same position in matrices A and B.

For example if I have 22 and 1 in position [1,1] in matrix A and B, I want to assign a value 1 at the same position in matrix C because both A and B have values above 0. Similarly for every values in C they are all dependent on whether values in matrices A AND B (in the same position) are above 0 or not. This is how my code looks like at the moment,

C<-matrix(0,100,100) #create a matrix with same dimensions and populated with 0
C[A>0 && B>0] = 1 

My matrix A satisfies the condition A>0 as there are some negative and some positive values, matrix B also satisfies the condition B>0 as some values are negative and some positive. However my code does not result in a matrix C with values of 0 and 1, even when I know there are some positions which meet the requirement of both matrix A and B being above 0. Instead the matrix C always contains 0 for some reason. Could any one let me know what I am doing wrong and how do I correct it or perhaps a different way to achieve this? Thanks

Upvotes: 0

Views: 183

Answers (2)

GregF
GregF

Reputation: 1392

Does C[A>0 & B>0] = 1 work? && returns a single value, but & is vectorized so it will work on each cell individually.

Upvotes: 1

Alex A.
Alex A.

Reputation: 5586

This may not be the most efficient way to do it, but it works.

C <- matrix(0, 100, 100)

for (i in seq_along(C))
    if (A[i] > 0 && B[i] > 0)
        C[i] <- 1

When you create a sequence along a matrix using seq_along(), it goes through all elements in column-major order. (Thereby avoiding a double for loop.) And since the elements of A, B, and C match up, this should give you what you want.

Upvotes: 0

Related Questions