필터 지우기
필터 지우기

Assignin in parfor loop

조회 수: 9 (최근 30일)
Sascha
Sascha 2013년 8월 18일
Hello everybody,
i have a problem with assignin in a parfor loop. For that I made a short example which explains the problem:
for i = 1:10
beta = i;
disp(beta);
end
parfor pi = 1:10
assignin('base','beta',pi);
disp(beta)
end
In the first loop beta gets values from 1 to 10, but in the parfor-loop beta always has value of 10. Why does this happen? I wanted to assignin for a variable as a input for simulink simulations.
Many thanks in advance,
Greetings
Sascha
  댓글 수: 2
Jan
Jan 2013년 8월 18일
I cannot image a situation, in which assignin is useful inside a parfor loop.
Sascha
Sascha 2013년 8월 18일
I tried to run multiple simulink simulations in parallel, as I have seen it in: http://blogs.mathworks.com/seth/2010/10/17/parallel-computing-with-simulink-running-thousands-of-simulations/#11

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

답변 (2개)

Walter Roberson
Walter Roberson 2013년 8월 18일
Doing an assignin('base') is going to change the value in the base workspace, but code executed in parallel is executed in a non-base workspace (because a new process if formed.)
I am surprised assignin() is allowed in a parfor. If the value being assigned varies from loop to loop, the result would be entirely dependent on the order the loops ended up being executed, which is not determinate in parfor()

Edric Ellis
Edric Ellis 2013년 8월 19일
When you run your code at the command-line, all of the FOR loop body is run in the base workspace - whereas the PARFOR body is not. So, your ASSIGNIN statement is operating correctly, but the second line of your PARFOR loop body is not running in the base workspace - so it actually sees the value of beta set by the prior FOR loop. If you change your PARFOR loop to:
parfor pi = 1:10
assignin('base','beta',pi);
disp(evalin('base', 'beta'));
end
You should get the expected behaviour. Simulink models should also correctly see the value that you assign.
  댓글 수: 1
Sascha
Sascha 2013년 8월 20일
Thanks for your answer. I already tried it with a simulink model. But it doesn't work as I expected, so the next step was to try it with disp, to see what values arre assigned to beta.
I tried it with simulink as in the following code-fragment:
parfor pi = 1:n
load_system('invertedPendulum');
assignin('base','beta',pi);
sim('invertedPendulum');
outputsParfor(pi) = simout;
end
figure;
for j = 1:n
plot(outputsParfor(j));hold all;
end
hold off;
But in the plot I noticed that there were n-plots, but all were plotted with a value of p=n.

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

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by