parfor code can not run after wrapping into a function

2 次查看(过去 30 天)
I have a very simple code snippet with parfor that runs alright:
c = cell(1, 10);
parfor ii = 1:10
c{ii} = 1;
end
but after wrapping it into a function by adding just one code line 'function tempFcn()', Matlab reports a syntax error: the output variable 'c' should not be used after the PARFOR loop(I'm using the chinese version, so may not be the exact words in english):
function tempFcn()
c = cell(1, 10);
parfor ii = 1:10
c{ii} = 1;
end
why is this? As I have to use a similar code snipnet in a function, how to solve this problem?

回答(1 个)

Raymond Norris
Raymond Norris 2022-11-24
Hi @Yulin, when you write your code without the function prototype
function tempFcn()
then as a script, MATLAB doesn't know if the variable c will be used in other functions/scripts or used at your command line. When you convert your script to a function, then MATLAB knows that, in your simple example, the variable c is not being used. In this case, the Code Analyzer will provide the following warning
The output variable 'c' might not be used after the PARFOR loop.
But keep in mind, this is just a warning -- this has no bearing on your code and ought to work fine.

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by