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

조회 수: 2 (최근 30일)
Kris Sarikanoppakhun
Kris Sarikanoppakhun 2021년 3월 28일
답변: Arjun 2025년 6월 5일
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

답변 (1개)

Arjun
Arjun 2025년 6월 5일
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!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by