The size of my final matrix is wrong in a nested loop

2 visualizaciones (últimos 30 días)
Andromeda
Andromeda el 2 de Abr. de 2022
Comentada: Stephen23 el 3 de Abr. de 2022
I am matching the first element in my matrix to each element in the matrix excluding itself, row to second column element to last. The final size of the resulting matrix is [1 2] instead of [7 2]. How do I fix this? I want a final size of [7 2]. Any help will be much appreciated
A = [1 2 3 4 5 6 7 8];
for c = 1:1:size(A,1)
row1 = A(c, 1);
for k = 2:1:size(A, 2)
columns = A(c, k);
Final = [row1 columns];
disp(size(Final))
end
end

Respuesta aceptada

Voss
Voss el 2 de Abr. de 2022
Is this what you want to do?
A = [1 2 3 4 5 6 7 8];
for c = 1:1:size(A,1)
row1 = A(c, 1);
Final = [];
for k = 2:1:size(A, 2)
columns = A(c, k);
Final = [Final; row1 columns];
disp(size(Final));
end
end
1 2 2 2 3 2 4 2 5 2 6 2 7 2
disp(Final);
1 2 1 3 1 4 1 5 1 6 1 7 1 8
  12 comentarios
Voss
Voss el 3 de Abr. de 2022
Move the line
Final = [];
to the top, outside of both loops.
In the previous case, there was only one row, so it didn't matter (and I didn't know what the result should be for a multiple-row matrix).

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements 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