parfor code can not run after wrapping into a function

1 visualización (últimos 30 días)
Yulin
Yulin el 23 de Nov. de 2022
Respondida: Raymond Norris el 24 de Nov. de 2022
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?

Respuestas (1)

Raymond Norris
Raymond Norris el 24 de Nov. de 2022
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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by