correction in order of elements in matrix obtained from reshape array

1 Ansicht (letzte 30 Tage)
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 Kommentare
David Fletcher
David Fletcher am 3 Apr. 2021
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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 3 Apr. 2021
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 Kommentar
Karanvir singh Sohal
Karanvir singh Sohal am 3 Apr. 2021
This is great!!!!
No need of for loop.
I gonna check the efficiency of this solution for different size of the matrix before using. :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Matt J
Matt J am 3 Apr. 2021
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 Kommentar
Karanvir singh Sohal
Karanvir singh Sohal am 3 Apr. 2021
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by