What is causing this intermittent error in parfor?

36 visualizaciones (últimos 30 días)
Chris
Chris el 8 de Dic. de 2025 a las 21:59
Editada: Matt J el 9 de Dic. de 2025 a las 13:04
The attached script produces an intermittent error:
Increasing n in untitled_script.m appears to increase the likelihood of the error occuring. Replacing parfor with for prevents the error from occuring. Setting n=1 prevents the error from occuring. Replacing "test(ii,1)=Test(input,ii);" with "Test(input,ii);" prevents the error from occuring.
Anyone understand what is going on here?
  1 comentario
Chris
Chris el 8 de Dic. de 2025 a las 22:10
Replacing "test(ii,1)=Test(input,ii);" with "test{ii}=Test(input,ii);" also appears to prevent the error from occuring.

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 9 de Dic. de 2025 a las 0:56
Editada: Matt J el 9 de Dic. de 2025 a las 1:04
If you add the indicated line, your class constructor will support no-argument calls, and the error will go away:
function obj = Test(inputArg1,ii)
arguments
inputArg1
ii = 2
end
if ~nargin, return; end %<---- Add this
display(num2str(ii))
obj = obj.method1(inputArg1);
end
This is necessary because the loop variable values ii in a parfor loop will not be visited in in sequential order, meaning that certain elements in the vector test will need to be populated temporarily with argument-free constructor calls.
  2 comentarios
Matt J
Matt J el 9 de Dic. de 2025 a las 1:01
Editada: Matt J el 9 de Dic. de 2025 a las 1:05
Alternattively (and perhaps preferably), pre-allocate the test array,
input.test_field=1;
input.test_field2=1;
n=3;
test(1:n,1)=Test(input); %<--- pre-allocate
parfor ii=1:n
test(ii,1)=Test(input,ii);
end
Chris
Chris el 9 de Dic. de 2025 a las 4:08
Thanks Matt!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Etiquetas

Productos


Versión

R2025b

Community Treasure Hunt

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

Start Hunting!

Translated by