Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
Andromeda
Andromeda am 2 Apr. 2022
Kommentiert: Stephen23 am 3 Apr. 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

Akzeptierte Antwort

Voss
Voss am 2 Apr. 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 Kommentare
Voss
Voss am 3 Apr. 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).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements 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