Dynamic for loops?

4 views (last 30 days)
Logan Perry
Logan Perry on 11 Jul 2018
Answered: Walter Roberson on 11 Jul 2018
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.

Accepted Answer

Walter Roberson
Walter Roberson on 11 Jul 2018
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

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!