correction in order of elements in matrix obtained from reshape array

1 回表示 (過去 30 日間)
Karanvir singh Sohal
Karanvir singh Sohal 2021 年 4 月 3 日
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
Karanvir singh Sohal
Karanvir singh Sohal 2021 年 4 月 3 日
This works fine. :)

サインインしてコメントする。

採用された回答

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 Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by