slicing multi-dimensionsal arrays

54 次查看(过去 30 天)
I am just trying to learn about manipulating multidimensional arrays in MATLAB. I feel like I am really not getting something...
Given these statements:
A = [1 2; 3 4];
B = [10 20; 30 40];
C = [42 3.14; 97 21];
I can build a 2x2x3 block like this:
ary3d(:,:,1) = A;
ary3d(:,:,2) = B;
ary3d(:,:,3) = C;
ary3d
ary3d(:,:,1) =
1 2
3 4
ary3d(:,:,2) =
10 20
30 40
ary3d(:,:,3) =
42 3.14
97 21
I want to collect each of the second rows into a 3x2 array. This can be accomplished like this:
squeeze(ary3d(2,:,:))'
ans =
3 4
30 40
97 21
but it seems odd to me that the transpose operator would need to be involved.
Stranger yet is the fact that all three of these commands give the same answer:
cat(1, ary3d(2,:,:))
cat(2, ary3d(2,:,:))
cat(3, ary3d(2,:,:))
I would have expected one of these commands to give a 2x3x1 array, one to give a 6x1x1, and one to give a 1x2x3 array. In fact, all three give this answer:
cat(3, ary3d(2,:,:))
ans(:,:,1) =
3 4
ans(:,:,2) =
30 40
ans(:,:,3) =
97 21
Can anybody shed any light here?
Is there some way (some relatively obvious way I ought to be seeing) to do this command without using the transpose operator?
squeeze(ary3d(2,:,:))'
ans =
3 4
30 40
97 21
Thanks, Erik
  1 个评论
Oleg Komarov
Oleg Komarov 2012-4-12
Could you please edit the EDU>> out to make the code copy-pastable?

请先登录,再进行评论。

采纳的回答

Oleg Komarov
Oleg Komarov 2012-4-12
Your input:
A = cat(3, [1 2; 3 4], [10 20; 30 40], [42 3.14; 97 21]);
1. The squeeze removes all singleton dimensions:
squeeze(A(2,:,:))
ans =
3 30 97
4 40 21
because A(2,:,:) selects one specific row, you have a (1 by) 2 by 3 slice.
2. Not strange at all since you're concatenating one slice with nothing else!
B = A(2,:,:)
B(:,:,1) =
3 4
B(:,:,2) =
30 40
B(:,:,3) =
97 21
B is one variable, not 3. Don't be fooled by the way it prints on the screen.
3. Not using the transpose:
permute(A(2,:,:), [3,2,1])
first comes the 3rd dim, then the 2nd and last the 1st.
It takes a little time to get used "visually". I suggest to draw things on paper.
  2 个评论
Erik
Erik 2012-4-12
Yes - I thought I was concatenating three different elements. I see what you mean now.
Erik
Erik 2012-4-12
Thank you for your answer.

请先登录,再进行评论。

更多回答(1 个)

Honglei Chen
Honglei Chen 2012-4-12
In your code, you only passed on data input to cat. You can try the following
cat(1,ary3d(2,:,1),ary3d(2,:,2),ary3d(2,:,3))

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by