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

조회 수: 8 (최근 30일)
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
K E
K E 2012년 8월 10일
편집: K E 2012년 8월 10일
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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Edric Ellis
Edric Ellis 2012년 8월 10일
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
K E
K E 2012년 8월 10일
In case it is helpful: you can generate all combinations of the parameter sets using allcomb on the File Exchange.

댓글을 달려면 로그인하십시오.


Jonathan
Jonathan 2012년 8월 21일
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.

카테고리

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