0

I found a simple way to replicate matrix dimensions but I do not understand it:

A=[1,2;3,4]  
A1=repmat(A,[1 1 2]); 

returns

A1(:,:,1)=[1 2; 3 4 ]    
A1(:,:,2)=[1 2; 3 4]

And if I do this

A2=A(:,:,[1 1])

it returns exactly the same result. Please can someone explain how and why this second method works?

Amro
  • 123,847
  • 25
  • 243
  • 454

1 Answers1

2

Lets look at a simpler example:

A = [1,2,3,4,5]*10;

Now I'm sure you'll agree that A(1) = 10, A(2) = 20 etc but we can also address a matrix using a vector of indices e.g. A([1,3]) returns [10,30] but you can also repeat indices and it will just address the same element twice: A([1,1]) returns [10,10].

Now lets add a dimension:

A = [1,2,3;
     4,5,6;
     7,8,9]*10;

So A(1,:) returns [10,20,30]. But what about A([1,1], :)? That's going to return the first row twice! So [10,20,30;10,20,30]

But what about the thrid dimension? A is a 3x3 2D matrix right? yes, but it's also a 3x3x1 3D matrix. So A == A(:,:,1), which means that by the same logic as above A(:,:,[1,1]) will just return that third dimension twice and hence is the same as repmat(A, [1,1,2]).

Dan
  • 45,079
  • 17
  • 88
  • 157