slicing multi-dimensionsal arrays

조회 수: 18 (최근 30일)
Erik
Erik 2012년 4월 12일
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))
  댓글 수: 1
Erik
Erik 2012년 4월 12일
Thank you - I think I see what is going on now.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by