Writing a for loop to run a single command for several different variables

14 ビュー (過去 30 日間)
Tom Halmos
Tom Halmos 2019 年 9 月 7 日
コメント済み: Jackson Burns 2019 年 9 月 8 日
I'm running a Gillespie Simulation and would like to execute a for loop using 'i' which takes a set of variables I give it in a matrix. Struggling to explain what I want to happen in code terminology. This is an example of the outcome I'd like:
A=[1,2]
B=[3,4]
for i = [A,B]
cat(2,i,5) (i.e I want to make 5 the next number in both A and B, so matlab would do cat(2,A,5) and cat(2,B,5)
end
This would ideally result in A=[1,2,5] and B=[1,2,5], but matlab doesn't read i=A as a variable, but as 1 and 2 then just does cat(2,1,5) and cat(2,2,5) (I think).
In the above case I could just write the cat command out twice but in the actual code doing it with a for loop will save a lot of extra work. Of course, if there is a better way to do this than with a for loop/cat comman please let me know.

採用された回答

Jackson Burns
Jackson Burns 2019 年 9 月 7 日
Hi Tom!
I'm guessing the issue you were having is that the for loop would iterate through all the elements of both lists individually. This is because calling the for loop with [A,B] concatenates the lists. To avoid this, I wrote a function that accomplishes the task using cell arrays:
function out = append5(in)
out = {};
for mat = in
out(end+1) = {[cell2mat(mat) 5]};
end
end
Try it out like this:
a = [1 2]; b = [3 4];
entry = {a,b};
answer = append5(entry)
To then remove the result from answer, use curly braces.
mat1 = answer{1}
Good luck, hope I helped!
  2 件のコメント
Tom Halmos
Tom Halmos 2019 年 9 月 7 日
Great thanks for that!
Jackson Burns
Jackson Burns 2019 年 9 月 8 日
You're welcome! Please accept the answer to the question if you found it helpful so that more people can find it in the future.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by