Reputation: 87
I have a vector s
, which is of size 1*163840
which comes from sizeX * sizeY * sizeZ = 64 * 40 * 60
. I want to convert the 1*163840 vector to a 3-dimensional matrix, which has 64 in x-axis, 40 in y-axis, and 64 in z-axis.
What is the easiest way to convert it?
Upvotes: 5
Views: 1909
Reputation: 114796
reshape
is the right way of re-aranging elements into a different shape, as pointed out by Ben.
However, one must pay attention to the order of the elements in the vector and in the resulting array:
>> v = 1:12;
>> reshape( v, 3, 4 )
1 4 7 10
2 5 8 11
3 6 9 12
Matlab arranges the elements "column first".
If you want to get a "row first" arrangement, you'll need to be a bit more sophisticated and use permute
as well
>> permute( reshape( v, 4, 3 ), [2 1] )
1 2 3 4
5 6 7 8
9 10 11 12
See how we reshape
to 4-by-3 (and not 3-by-4) and then transpose the result using permute
command.
Upvotes: 1
Reputation: 33864
Use reshape to do it easily:
new_matrix = reshape(s, 64, 40, 60);
Upvotes: 4
Reputation: 9
initialize the matrix like so:
smatrix=zeros(64,40,60) // here you get an empty 3D matrix of the size you wanted.
use for loops to populate the matrix using your vector
for indexx=1:64
for indexy=1:40
for indexz=1:60
smatrix(indexx,indexy,indexz)=s(40*60*(indexx-1)+60*(indexy-1)+indexz);
end
end
end
Upvotes: 0