Clear Filters
Clear Filters

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

2 views (last 30 days)
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

Accepted Answer

Voss
Voss on 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 Comments
Voss
Voss on 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).

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!