[英]How to convert matlab vector to 3D matrix
我有一个向量s
,大小为1*163840
,来自sizeX * sizeY * sizeZ = 64 * 40 * 60
。 我想将1 * 163840向量转换为3维矩阵,该矩阵在x轴上有64个,在y轴上有40个,在z轴上有64个。
转换它的最简单方法是什么?
使用重塑可以轻松做到:
new_matrix = reshape(s, 64, 40, 60);
如Ben所指出的, reshape
是将元素重新排列为不同形状的正确方法。
但是,必须注意向量中和结果数组中元素的顺序:
>> 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
命令转置结果。
像这样初始化矩阵:
smatrix=zeros(64,40,60) // here you get an empty 3D matrix of the size you wanted.
使用循环使用向量填充矩阵
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.