필터 지우기
필터 지우기

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

조회 수: 7 (최근 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.

채택된 답변

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
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by