correction in order of elements in matrix obtained from reshape array

1 visualización (últimos 30 días)
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 comentarios
David Fletcher
David Fletcher el 3 de Abr. de 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

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 3 de Abr. de 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 comentario
Karanvir singh Sohal
Karanvir singh Sohal el 3 de Abr. de 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. :)

Iniciar sesión para comentar.

Más respuestas (1)

Matt J
Matt J el 3 de Abr. de 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 comentario
Karanvir singh Sohal
Karanvir singh Sohal el 3 de Abr. de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by