reshape function with index 1

조회 수: 1 (최근 30일)
Raz Firanko
Raz Firanko 2020년 12월 13일
편집: Raz Firanko 2022년 2월 20일
Hey
Suppose I have an array, let's say
A=[1 0 ; 0 1];
And I want to increase it's size, that is, to make it a 2x2x1 array:
B=reshape(A,[2 2 1])
However, the reshape dunction is fixing my size at 2x2.
Do you guys know how to make it work? thanks

채택된 답변

John D'Errico
John D'Errico 2020년 12월 13일
편집: John D'Errico 2020년 12월 13일
Reshape worked perfectly.
In fact, you never had to do any reshape at all. Why is that?
Because ALL arrays in MATLAB are assumed to have infinitely many trailing singleton dimensions. So a 2x2 array actually has dimension 2x2x1x1x1x1x1x1...
All that is reported for 2-d arrays are the first two dimensions. So your 2x2x1 array really is the size you wanted.
A = eye(2);
A(2,2,1)
ans = 1
So in fact, MATLAB does recognize that A can be indexed already using the third dimension, even when it reports A as being 2x2.
size(A)
ans = 1×2
2 2
size(reshape(A,[2 2 1]))
ans = 1×2
2 2
If we force A to have a non-singleton third dimension, this of course works.
size(reshape(A,[1 2 2]))
ans = 1×3
1 2 2
As you see, now MATLAB knows the result does have 3 dimensions. It always did know that though.
A = eye(2);
A(1,2,1,1,1,1,1,1,1,1)
ans = 0
  댓글 수: 2
Raz Firanko
Raz Firanko 2020년 12월 13일
Thank you for the answer, I'll keep that in mind!
John D'Errico
John D'Errico 2020년 12월 13일
편집: John D'Errico 2020년 12월 13일
I should have added, this goes back to the early versions of MATLAB, when arrays were never more than 2-dimensions. Then higher dimensional arrays were added as a capability.
I also see you mentioned something about increasing the size of an array, essentially adding planes to an array.
So we can simply add a new plane to an array. Here, that plane will be entirely zero.
A = eye(2);
A(2,2,2) = 0
A(:,:,1) =
1 0
0 1
A(:,:,2) =
0 0
0 0
Or we can replicate the array into the third dimension.
A = magic(2);
repmat(A,[1,1,2])
ans(:,:,1) =
1 3
4 2
ans(:,:,2) =
1 3
4 2
Or we can concatenate two arrays, as planes.
A = eye(2);
B = magic(2);
C = cat(3,A,B)
C(:,:,1) =
1 0
0 1
C(:,:,2) =
1 3
4 2

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by