slicing multi-dimensionsal arrays

49 views (last 30 days)
Erik
Erik on 12 Apr 2012
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 Comment
Oleg Komarov
Oleg Komarov on 12 Apr 2012
Could you please edit the EDU>> out to make the code copy-pastable?

Sign in to comment.

Accepted Answer

Oleg Komarov
Oleg Komarov on 12 Apr 2012
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 Comments
Erik
Erik on 12 Apr 2012
Yes - I thought I was concatenating three different elements. I see what you mean now.
Erik
Erik on 12 Apr 2012
Thank you for your answer.

Sign in to comment.

More Answers (1)

Honglei Chen
Honglei Chen on 12 Apr 2012
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))
  1 Comment
Erik
Erik on 12 Apr 2012
Thank you - I think I see what is going on now.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!