0
a = [1 2 3;
     4 5 6;
     7 8 9];

b = [10 11 12;
     13 14 15;
     16 17 18;
    ];

c = [19 20 21;
     22 23 24;
     25 26 27;
    ];

I want to combine the above 2D matrices into a 3D matrix mat so that I can access them in the following way,

>> mat(:, :, 1)
ans = 
[1 2 3
 4 5 6
 7 8 9]

>> mat(:, :, 2) 
ans = 
[10 11 12
 13 14 15
 16 17 18]

>> mat(:,:,3)
ans = 
[19 20 21
 22 23 24
 25 26 27]

I tried the following,

mat = [a, b, c];

But, it actually doesn't work.

So, how can I achieve that?

m7913d
  • 10,244
  • 7
  • 28
  • 56
user366312
  • 16,949
  • 65
  • 235
  • 452
  • In addition to the answers read the documentation associated with `cat` to get more ideas of ways to combine things. – Matt Jul 12 '17 at 19:57
  • @hbaderts: Hmm, wonder why that didn't show up on the "Related" sidebar. – gnovice Jul 12 '17 at 20:14

2 Answers2

5

Square brackets [] are for horizontal and vertical concatenation of matrices. You can use the cat function for concatenating along higher dimensions:

mat = cat(3, a, b, c);

More info can be found here.

gnovice
  • 125,304
  • 15
  • 256
  • 359
3

You can do it as follows using explicit matrix indexing:

mat(:,:,1) = a;
mat(:,:,2) = b;
mat(:,:,3) = c;

mat = [a, b, c]; will create a 3x9 matrix.

m7913d
  • 10,244
  • 7
  • 28
  • 56