1

I have a question about modifying a matrix. I have managed to change values in a matrix depending on the value of another matrix when they are of the same dimension. But now I need to apply this procedure to matrixes with different dimensions. In other words, I want to apply some changes to a "region" of the bigger matrix depending on the values of the smaller one, bearing in mind that I know the positions of the smaller matrix associated to the bigger one.

Suppose this are matrix A

1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 

and B

 0 0 0 0 0 0 
 0 1 1 1 1 0 
 0 0 1 1 1 0 
 0 0 1 1 0 0 
 0 0 0 0 0 0 

I know that B[1,1] is the value I have to check to modify A[2,1], B[2,1] for A[3,1] and so on...

The final result I am looking for is

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

For the A values replacement I use a for loop in my original script

for (i in 1:10) A[B == i] = 0

that works when A and B have same dimension.

How should I make the replacement in matrix A? apply? a for loop?

Any help would be appreciated and of course you can point me to some basic reading I haven't still read.

pacomet
  • 5,011
  • 12
  • 59
  • 111
  • How would an algorhithm know where to place the "empty" region? From the computer's point of view, he could shift the small matrix left or right. – Roman Luštrik Sep 21 '11 at 13:24
  • @RomanLuštrik Hi, my data are on a geographical grid so I have the lat-lon coords for each point. So I can compute which row and column from both matrixes are in the same geographical point – pacomet Sep 21 '11 at 19:15
  • 1
    I would suggest to look at the Spatial Task View. Package `sp` has classes to handle spatial data. http://cran.r-project.org/web/views/Spatial.html What you're trying to achieve is basically "masking". – Roman Luštrik Sep 21 '11 at 19:37
  • OK Roman, I'll look at sp package, thanks – pacomet Sep 22 '11 at 08:36

1 Answers1

2

Just select the submatrix and do what you want, i.e.:

A[1:5,2:8][B == 1] = 0

Or, in general, if [row, col] is the starting position of matrix B in matrix A:

A[row:nrow(A),col:ncol(A)][B == 1] = 0

Here is the test code so that you can check it works:

A = matrix(rep(1:8, each = 5), nrow = 5)
B = matrix(c(rep(0, 7), 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, rep(0, 8)), nrow = 5, byrow = TRUE)
A[1:5,2:8][B == 1] = 0

Thanks to Andrie ho for hinting me the ncol function instead of ugly dim(A)[2]...

Community
  • 1
  • 1
Tomas
  • 57,621
  • 49
  • 238
  • 373
  • Thanks Tomas, your example runs fine. It is exactly what I needed. Tomorrow at work I will try with my data. – pacomet Sep 21 '11 at 19:22