1

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].

Anu
  • 211
  • 1
  • 9

2 Answers2

2

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)
DJack
  • 4,850
  • 3
  • 21
  • 45
  • It's working. I am wondering how important the transpose here. I tried your method without doing transpose. It was wrong. Nice solution @DJack. – Anu Apr 23 '18 at 17:21
0

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)
rg255
  • 4,119
  • 3
  • 22
  • 40
  • 1
    Interesting approach but it should be `matrix(c(t(A)[1:8], t(B)[9:15]), byrow = T, ncol = 3)`. – DJack Apr 23 '18 at 17:39