Change 1D vector (nx1) to 3D matrix (1x1xn)

落爺英雄遲暮 提交于 2020-01-02 07:18:07

问题


Given a= [1;2;3] I want to change this to b where b is

b(1,1,1) = 1
b(1,1,2) = 2
b(1,1,3) = 3.

How can I do this? Is there no built-in command for this?


回答1:


Use permute to throw the first dimension back at the end as third dimension and bring the third and second dimensions to the front (their orders won't matter). Thus, we would have two such implementations, like so -

permute(a,[3 2 1])

permute(a,[2 3 1])

You can also use reshape to push back the elements to the third dimension, like so -

reshape(a,1,1,numel(a))

Little tutorial on permute

A 3D array A without any permute(rearrangement of dimensions) changes would be : permute(A,[1 2 3]).

Now, any permuting you do, would be w.r.t. the original order of [1 2 3]. Let's say you want to swap 1st and 3rd dimensions, so swap the 1 and 3 in [1 2 3], giving us [3 2 1] and use it as the second argument in permute.

Here's to make your permuting skills stronger - Let's say, you swap first and third dimensions and then you do some processing on this permuted 3D array. Now, you want to get back to the original order, so you need to swap back the 1st and 3rd dimensions. So, you use [3,2,1] again, like so - permute(permute(A,[3 2 1]),[3 2 1]) and this would be essentially permute(A,[1 2 3]) and yes that's A, back to home!




回答2:


You can also use

b = shiftdim(a,-2);

As per the documenation,

B = shiftdim(X,N) shifts the dimensions of X by N. When N is positive, shiftdim shifts the dimensions to the left and wraps the N leading dimensions to the end. When N is negative, shiftdim shifts the dimensions to the right and pads with singletons.

A singleton dimension [or simpliy "singleton"] is any dimension dim for which size(A,dim) = 1.



来源:https://stackoverflow.com/questions/32732524/change-1d-vector-nx1-to-3d-matrix-1x1xn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!