Reputation: 1457
I have this vector:
arr = [1; 2; 3; 1; 2; 3; 1; 2; 3; 1; 2; 3]
And would like to turn it into a 4x3 matrix looking like this:
mat = [1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3;...
1 1 1;...
2 2 2;...
3 3 3]
So far I achieved this by doing:
a1 = arr(1:3:end);
a2 = arr(2:3:end);
a3 = arr(3:3:end);
mat = [a1 a2 a3];
Is there a more convenient way with for instance the reshape
function?
Upvotes: 1
Views: 29
Reputation: 3801
reshape
does not change the number of the elements in a matrix. It reshapes the matrix by rearranging the existing elements.
In your case, you can use repmat
, which copies a matrix or vector one or multiple times:
mat = repmat(arr,1,3);
You can read more about repmat
here.
Also, your solution does not give the matrix you showed in the code block. To get the result given by your solution, you can use reshape
as such:
mat = reshape(arr,3,4)'
Upvotes: 2