How to convert a Matlab vector to a 3D matrix

I have a vector sthat has a size 1*163840that comes from sizeX * sizeY * sizeZ = 64 * 40 * 60. I want to convert a 1 * 163840 vector to a 3-dimensional matrix that has 64 on the x axis, 40 on the Y axis and 64 on the z axis.

What is the easiest way to convert it?

+4
source share
3 answers

Use the form to simplify:

new_matrix = reshape(s, 64, 40, 60);
+4
source

reshapeis the correct way to rearrange items into a different form, as indicated by Ben .
However, you should pay attention to the order of 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 "".
" ", permute,

>> permute( reshape( v, 4, 3 ), [2 1] ) 
 1     2     3     4
 5     6     7     8
 9    10    11    12

, reshape 4--3 ( 3--4), permute.

+1

initialize the matrix as follows:

smatrix=zeros(64,40,60) // here you get an empty 3D matrix of the size you wanted. 

use for loops to fill the matrix with 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
0
source

Source: https://habr.com/ru/post/1547354/


All Articles