For loop over written output

Hello,
I seem to keep running into this problem again and again. So I would really appreciate if someone could explain what I should do here?
Every time the outer for loop (i=1:s_m) runs, it overwrites the results from the previous nested for loop run (k=1:s). How can I solve this so that the results go in the subsequent column regardless of how many times I run the outer loop?
For the final answer, I want an array (Z) with 3 cols, and as many number of rows as needed (depending on user input). Currently Z has 500 rows because I initialized to an arbritaty overly conservative number.
Please help! I am really new to MATLAB (2018b). I don't just want an answer to this specific problem. I would really like to understand how to get for loops to not overwrite solutions in general.
matches=cell array; reactionType=string array
matches=L(idx);
s_m=length(matches);
Z=cell(500,3);
for i=1:s_m
s=length(matches{1,i});
for k=1:s
q(k)=matches{1,i}(k,1);
Z(k,1)={q(k)};
Z(k,2)={reactionType(q(k),3)};
Z(k,3)={reactionType(q(k),2)};
end
end

 Accepted Answer

matches = L(idx);
s_m = length(matches);
num_matches = arrayfun(@length, matches);
Nz = sum(num_matches);
Z = cell(Nz,3);
r = 0;
for i = 1:s_m
s = num_matches(i)
for k = 1:s
q = matches{1,i}(k,1);
r = r + 1;
Z{r, 1} = q;
Z{r, 2} = reactionType(q,3);
Z{r, 3} = reactionType(q,2);
end
end

More Answers (0)

Categories

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

Products

Release

R2018b

Tags

Community Treasure Hunt

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

Start Hunting!