correction in order of elements in matrix obtained from reshape array

1 view (last 30 days)
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 Comments
David Fletcher
David Fletcher on 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

Sign in to comment.

Accepted Answer

Matt J
Matt J on 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 Comment
Karanvir singh Sohal
Karanvir singh Sohal on 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. :)

Sign in to comment.

More Answers (1)

Matt J
Matt J on 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 Comment
Karanvir singh Sohal
Karanvir singh Sohal on 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.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!