How to Concatenate the result in for loop?

9 views (last 30 days)
Hello every one
I'm very new in matlab
I have some problem how do i concatenate the result from for loop?
for i=0:bond(860) %bond is the data table include 861*36 table of number
a=[bond(i+1,:)];
B=[repmat(a(1),[length(nonzeros(a))-1 1]) nonzeros(a(2:end)')];
end
the result is
B =
16×2 uint32 matrix
860 796
860 797
860 798
860 816
860 817
860 818
860 819
860 836
860 837
860 838
860 839
860 840
860 857
860 858
860 859
860 861
B =
12×2 uint32 matrix
861 797
861 798
861 817
861 818
861 819
861 837
861 838
861 839
861 840
861 858
861 859
861 860
This is a few result it have number 1 - 861
it show just the lastest result in B table
I want to get all result since 1 to 861 in the same arrey (concatenate all result in one table), want all result in B table not only the lastest calculation

Answers (1)

Arjun
Arjun on 2 Jun 2025
As per my understanding, the issue is that you are overwriting the variable "B" in each iteration of the loop and because of that result from the last iteration remains in variable "B".
To concatenate result from every iteration into "B", you need to initialize "B" before the loop and then instead of overwriting you append the fresh results into "B" in each iteration. Kindly refer to the modified version of the code below:
B = []; % Initialize B before the loop
for i = 0:bond(860)
a = bond(i+1, :);
temp = [repmat(a(1), [length(nonzeros(a)) - 1, 1]), nonzeros(a(2:end)')]; % Storing result of this iteration in a temporary variable
B = [B; temp]; % Append the result to B
end
% At the end of the loop B will contain the result concatenated from all
% the iterations
I hope this helps!

Categories

Find more on Tables 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!