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

 採用された回答

Walter Roberson
Walter Roberson 2018 年 12 月 31 日

0 投票

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

1 件のコメント

Ishita Trivedi
Ishita Trivedi 2019 年 1 月 5 日
what does @arrayfun(...) do?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2018b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by