How to modify code to use parfor rather than more than two nested for loops?

Hi All
I am having a problem wrapping my head around using parfor command with more than one nested for loop.
The article: http://blogs.mathworks.com/seth/2010/10/17/parallel-computing-with-simulink-running-thousands-of-simulations/ is very informative and uses meshgrid to give the correct index values. However this is only valid if replacing two for loops with parfor.
I am currently running a parameter sweep with a simulation in Simulink, which I call from matlab. There are 6 variables I am iterating, with 8 values for each. Each simulation is independent of one another. The dependency only comes in because I am using the for loops to iterate through the parameters. I have attached an example of what I mean below.
Any help with speeding up the process, or help with understanding what I need to be doing would be greatly appreciated.
Thanks
% code
for c1=1:itrsize
for c2=1:itrsize
[Css]=DSpec2(c1,c2,MRr);
Csrs=[Css(:,1),Css(:,2)];
for c3=1:itrsize
for c4=1:itrsize
[Css]=DSpec2(c3,c4,MRr);
Csfs=[Css(:,1),Css(:,2)];
for c5=1:2
f=Springs(c5);
for c6=1:2
r=Springs(c6);
sim('Example') %Run Simulation
end
end
end
end
end
end

1 Comment

If I could give this question 5 votes I would! This is the main barrier to using parfor on legacy code which might have 5-6 nests of parameters.

Sign in to comment.

Answers (2)

I think you should be able to solve this problem by using linear indexing - i.e. taking advantage of MATLAB's ability to index arrays using fewer than the 'natural' number of subscripts. For example,
inputData = rand(4, 5, 6, 7); % 4-D input data
outputData = zeros(size(inputData)); % output same size and shape
% use a single loop over all elements of 'inputData'
parfor ii = 1:numel( inputData )
outputData(ii) = myCalculation( inputData(ii) );
end
Note that by pre-allocating 'outputData', we ensure it ends up the correct shape.

1 Comment

In case it is helpful: you can generate all combinations of the parameter sets using allcomb on the File Exchange.

Sign in to comment.

Hi guys
Thanks for the comments.
Edric, I dont really understand what you were preposing. It does sound abit like the method proposed by K E.
K E what you're proposing makes a lot of sense. In a way, I just used my existing for loops to iterate the variables and then save them in a much larger matrix. I then saved this as just call it prior to running the program. Thanks for the file.
I can now use the parfor loop for the time consuming simulation.

Categories

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

Asked:

on 9 Aug 2012

Community Treasure Hunt

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

Start Hunting!