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

4 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Jackson Burns
Jackson Burns am 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!
  2 Kommentare
Jackson Burns
Jackson Burns am 8 Sep. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by