Writing a for loop to run a single command for several different variables
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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 个评论
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!