필터 지우기
필터 지우기

C-order reshape of multi-dimensional array in matlab

조회 수: 41 (최근 30일)
Yijun Li
Yijun Li 2019년 3월 10일
댓글: Stephen23 2022년 9월 7일
Hello,
I have a question regarding reshape in matlab, it seems that matlab reshapes N-dimensional array according to Fortran-order, however, I would like a C-order reshape, that is a line-wise reshape.
Suppose now there is a matrix M with 4 rows and 4 columns as follows:
M = [1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16]
Then M is going to be reshaped to a 3D array with dimension (2,2,4) shown in the picture below. Does anyone know how to do this in a generalized way (suitable for even higher dimension)?
Thanks!
reshape_problem_2.jpg

채택된 답변

Jan
Jan 2019년 3월 10일
편집: Jan 2019년 3월 10일
Reshaping in line-wise order is not meaningful, because reshaping means to keep the order of elements in the memory and the order is defined columnwise in Matlab. But you can simply change the order by permute:
x = rand(2,3,4);
y = permute(x, [2, 1, 3:ndims(x)]);
result = reshape(y, [whateverYouWant])
  댓글 수: 7
Steven Lord
Steven Lord 2022년 9월 7일
That's the mapping between the dimensions of your original array and the dimensions of the result.
A = reshape(1:24, [4 3 2]);
szA = size(A)
szA = 1×3
4 3 2
p = [2 1 3];
B = permute(A, p);
szB = size(B)
szB = 1×3
3 4 2
A is size 4 in its first dimension. Because the first element of p is 2, B is size 4 in its 2nd dimension.
A is size 3 in its second dimension. Because the second element of p is 1, B is size 3 in its 1st dimension.
I was very careful to distinguish first and second from 1st and 2nd in those descriptions.
Stephen23
Stephen23 2022년 9월 7일
"Therefore I do not understand, why my code "fails the mission"."
I accepted your answer, Jan, because it is clear that permuting the first two dimensions is the general solution.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by