How to display all answer and connect result from for loop?

7 views (last 30 days)
Hello everyone I'm newbie of matlab program,i need some help from you guys. This code below is form loop of my result but it show answer just last step of loop so i want to know how to display all answer. Next question is how can i connect the result for more cleary i will show example result:
For example result
B= 1 2
4×2 uint32 matrix 1 3
1 2 1 4
1 3 2 3
1 4 2 4
B= 2 5
36×2 uint32 matrix
2 3
2 4
2 5
to be like right side
Thank you everyone
for i=0:bond(860) %bond is file that include of data
a=[bond(i+1,:)];
B=[repmat(a(1),[length(a)-1 1]) a(2:end)']
end

Answers (1)

Arjun
Arjun on 5 Jun 2025
The reason you're only seeing the result from the last iteration of the loop is that the variable "B" is being overwritten during each iteration. As a result, once the loop finishes, "B" only contains the data from the final step.
To retain the results from all iterations, you can use a separate variable—let’s call it "B_All"—and append each iteration’s result to it. This way, "B_All" accumulates the output across the loop, preserving the full set of results.
Kindly refer to the code snippet below:
B_All = []; % Initialize an empty matrix to store all results
for i = 0:bond(860)
    a = bond(i+1, :);
    B = [repmat(a(1), [length(a)-1, 1]), a(2:end)'];
    B_All = [B_all; B]; % Append current B to the full result
end
disp(B_All); % Contains results from each iteration
I hope this helps!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!