问题
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 ofX
byN
. WhenN
is positive,shiftdim
shifts the dimensions to the left and wraps theN
leading dimensions to the end. WhenN
is negative,shiftdim
shifts the dimensions to the right and pads with singletons.A singleton dimension [or simpliy "singleton"] is any dimension
dim
for whichsize(A,dim) = 1
.
来源:https://stackoverflow.com/questions/32732524/change-1d-vector-nx1-to-3d-matrix-1x1xn