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

13 views (last 30 days)
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.

Accepted Answer

Jackson Burns
Jackson Burns on 7 Sep 2019
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!

More Answers (0)

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!