correction in order of elements in matrix obtained from reshape array

조회 수: 1 (최근 30일)
Hello everyone!
below is the code for calculation of C
A=[4 4 4; 8 8 8]
B=[16 12 8]
[mA,nA] = size(A);
[mB,nB] = size(B);
index=0;
for i=1:mA
for j=1:nB
index=index+1;
c(index)=(min(A(i,j),B(1,j))/max(A(i,j),B(1,j)));
end
end
C=[reshape(c,[],nB)]
I'm obtaining this matrix
C = [0.2500 0.5000 0.6667
0.3333 0.5000 1.0000]
but i want results as
C = [0.2500 0.3333 0.5000
0.5000 0.6667 1.0000]
  댓글 수: 2
David Fletcher
David Fletcher 2021년 4월 3일
It's due to the way reshape fills the reshaped matrix from the elements of the original. To get it to do what you want you could reshape to a 3x2 matrix and then transpose
reshape(c,[],numel(c)/nB)'
ans =
0.2500 0.3333 0.5000
0.5000 0.6667 1.0000

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

채택된 답변

Matt J
Matt J 2021년 4월 3일
A loop-method,
A=[4 4 4; 8 8 8];
B=[16 12 8];
c=min(A,B(1,:))./max(A,B(1,:))
c = 2×3
0.2500 0.3333 0.5000 0.5000 0.6667 1.0000
  댓글 수: 1
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 3일
This is great!!!!
No need of for loop.
I gonna check the efficiency of this solution for different size of the matrix before using. :)

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

추가 답변 (1개)

Matt J
Matt J 2021년 4월 3일
A=[4 4 4; 8 8 8]
A = 2×3
4 4 4 8 8 8
B=[16 12 8]
B = 1×3
16 12 8
[mA,nA] = size(A);
[mB,nB] = size(B);
index=0;
for j=1:nB
for i=1:mA
index=index+1;
c(index)=(min(A(i,j),B(1,j))/max(A(i,j),B(1,j)));
end
end
C=reshape(c,[],nB)
C = 2×3
0.2500 0.3333 0.5000 0.5000 0.6667 1.0000
  댓글 수: 1
Karanvir singh Sohal
Karanvir singh Sohal 2021년 4월 3일
Thanks @Matt J
This is just a simple trick that works as my rquirement.
But using this as a solution maybe risky, if I forgot to switch the loops it may cause errors.

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by