Anu
Anu

Reputation: 211

R: Map a matrix with another matrix in r

I found a same question in map a matrix with another matrix. But, that is in Matlab. If I want to map a matrix with another matrix in R, How can I easily get without using a loop. For example, I have following matrices,

A = [ 1 4 3
      2 3 4 
      4 3 1 
      4 5 5 
      1 2 1]

 B = [3 3 2
      2 0 1
      1 1 5
      4 1 3
      5 2 0]

My mapping should be as given bellow;

  R = [1 4 3
      2 3 4
      4 3 5
      4 1 3
      5 2 0]

The result R will take the values from A starting from [1,1] to [3,2]. Then remaining values are from B starting from [3,3] to [5,3].

Upvotes: 1

Views: 390

Answers (2)

rg255
rg255

Reputation: 4169

A little different to Djack's approach, I used matrix with a byrow = T, and indexed the original matrices:

matrix(c(t(A)[1:8], t(B)[9:15]), byrow = T, ncol = 3)

Upvotes: 0

DJack
DJack

Reputation: 4940

As simple as:

R <- t(A)
R[9:15] <- t(B)[9:15]
t(R)
     [,1] [,2] [,3]
[1,]    1    4    3
[2,]    2    3    4
[3,]    4    3    5
[4,]    4    1    3
[5,]    5    2    0

Sample data

A <- matrix(c(1,4,3,2,3,4,4,3,1,4,5,5,1,2,1), nrow = 5, ncol = 3, byrow = TRUE)
B <- matrix(c(3,3,2,2,0,1,1,1,5,4,1,3,5,2,0), nrow = 5, ncol = 3, byrow = TRUE)

Upvotes: 2

Related Questions