parfor code can not run after wrapping into a function

1 回表示 (過去 30 日間)
Yulin
Yulin 2022 年 11 月 23 日
回答済み: Raymond Norris 2022 年 11 月 24 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by