Dynamic for loops?
조회 수: 3 (최근 30일)
이전 댓글 표시
So my question is a bit complicated so hopefully I will be able to describe it adequately. I currently have a function that takes in parameter values a, b, c, d and returns vectors x, y. I am plotting the results for a wide range of parametric combinations. For plotting reasons I need the user to be able to specify the order the for loops occur. This is because I want to produce figures that uses subplot to display graphs for all the plots of two of the variables in a single figure. I think it will make more sense if I write a short pseudo-code.
EXAMPLE:
a = [1,2];
b = [3,4,5];
c = [6,7,8];
d = [9,10,11,12];
XAXIS = ‘a’
YAXIS = ‘b’
for ci=1:length(c)
for di=1:length(d)
CASE = 0;
for ai=1:length(a)
for bi=1:length(b)
CASE = CASE+1
[x,y] = myfunction(a(ai),b(bi),c(ci),d(di));
figure(1)
subplot(length(a),length(b),CASE)
plot(x,y)
end
end
%SOME CODE TO SAVE THE CURRENT GRAPH TO A FILE
end
end
So the above code would save 12 figures that each had a 2x3 grid of plots. Is there a way to generalize the above code so that the user can specify XAXIS and YAXIS and have those two variables be the last ones looped over? I tried to put the for statement inside an eval, but matlab refuses to run it because it doesn’t match up right with the end statements. I feel like I am not explaining this well and so I would be happy to provide additional details if wanted.
댓글 수: 0
채택된 답변
Walter Roberson
2018년 7월 11일
Create a cell array of the variables. Create a vector of order indices according to user input.
paramcell = {a, b, c, d};
paramlengths = cellfun(@length, paramcell);
order = randperm(4); %except use user input to decide the order
vals = cell(1,4);
for idx1 = 1 : paramlengths(order(1))
vals{order(1)} = paramcell{order(1)}(idx1);
for idx2 = 1 : paramlengths(order(2))
vals{order(2)} = paramcell{order(2)}(idx2);
CASE = 0;
for idx3 = 1 : paramlengths(order(3))
vals{order(3)} = paramcell{order(3)}(idx3);
for idx4 = 1 : paramlengths(order(4))
vals{order(4)} = paramcell{order(4)}(idx4);
CASE = CASE+1;
[x, y] = myfunction( vals{:} );
...
end
end
end
end
댓글 수: 0
추가 답변 (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!