Is there a usual way to imitate return in parlor in Matlab?

The body of a parfor-loop element cannot contain a return statement.

I feel that someday it may be convenient, for example:

if matlabpool('size') == 0 % checking to see if my pool is already open
    matlabpool(2)
end

parameters = random_parameters(1000)
parfor i=1:1000
    result = do_stuff(parameters(i))
    if result < threshold
        return parameters
    end
end

Is there a common way to imitate a return to parfor?

I am using Matlab R2014a for Windows 7 SP1 x64 Ultimate.

+4
source share
1 answer

I use a try-catch block in such cases. Example:

rng('shuffle')
try parpool('local'); end % try block to avoid reinitiation of parpool
parameters = normrnd(0,1,1000,1);
threshold=0.95;
FoundParameter=NaN;
try
    parfor iParam=1:1000
        result = sin(parameters(iParam))
        if result < threshold
            error(num2str(parameters(iParam)))
        end
    end
catch err
    FoundParameter=str2num(err.message);
end
if isnan(FoundParameter)
    fprintf('\nGood parameter was not found\n')
else
    fprintf('\nGood parameter is: %f\n',FoundParameter)
end

PS Do not use i and j as iteration variables. This is bad practice at MatLab.

+1
source

Source: https://habr.com/ru/post/1629736/


All Articles