Franck Dernoncourt
Franck Dernoncourt

Reputation: 83317

Is there any usual way to imitate a return in a parfor in Matlab?

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

I feel it could be convenient sometime, e.g.:

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 any usual way to imitate a return in a parfor?

I use Matlab R2014a on Windows 7 SP1 x64 Ultimate.

Upvotes: 4

Views: 490

Answers (1)

zlon
zlon

Reputation: 834

I use try-catch block in such cases. Some 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

P.S. Please, do not use i and j as iteration variables. It is bad practice in MatLab

Upvotes: 1

Related Questions