(par)for k=1:N end; select for or parfor loop without code replication

조회 수: 5 (최근 30일)
Simon
Simon 2023년 8월 23일
댓글: Simon 2023년 8월 24일
I like to use for-loop or parfor-loop with function input flag. One way to do that is using if-else with code replication. I wonder is there a cleverer way?
% solution based on code replication
function foo(parflag)
if parflg==true
parfor k=1:3
% processing codes
end
else
for k=1:3
% copy of processing codes
end
end
end
%% wondering how to make this idea work?
function hoo(parflag)
if parflag==true
forString = str2func('parfor')
else
forString = str2func('for')
end
forString k=1:3
% processing codes
end
end

채택된 답변

Matt J
Matt J 2023년 8월 23일
편집: Matt J 2023년 8월 23일
You can avoid replicating the loop code as follows.
numWorkers={}; % or whatever
if ~parflag
numWorkers={0};
end
parfor (k=1:3, numWorkers{:})
% processing codes
end
Be mindful, though, that parfor loops have stronger requirements on the code structure, and you would be limiting yourself to that, even when running serially.
  댓글 수: 13
Bruno Luong
Bruno Luong 2023년 8월 24일
But then you have to manually set numWorkers
Simon
Simon 2023년 8월 24일
Yes, that flexibility works for me. For example, when I am not doing anything but programming Matlab, I can set it to the maximum number of workers my compouter has. But when I heavily multitask, I can set numWorkers, say, 2 or 3, and let other cores to work on non-Matlab tasks. (I guess that's how my Mac would work.)

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by