Philippe Remy
Philippe Remy

Reputation: 3153

How to gather results with parfor in MATLAB

I have a function called SpreadFinder which returns an array of structures:

[ spreads ] = SpreadFinder( pp, corr_thres, i_range )

The return object looks like this:

spreads = 
1x4026 struct array with fields:
px
tuple
beta

The code is:

m = containers.Map(0, 0, 'uniformValues',false); m.remove(0);
parfor col = 1:8
    spreads = SpreadFinder(pp, 0.8, i_ranges(:,col)');
    m(col)  = spreads;
end

When I run it, I have this error:

Subscripted assignment dimension mismatch.

I know the Map can be used to store an array of structures. (https://stackoverflow.com/a/2365526)

This code below works. So I don't think it's a problem of dimension...

m(1) = spreads(1:2);
m(2) = spreads(1:4);

The objective is to merge all the results into one map and possibly iterate over this map after the parallel task.

Can someone help me out?

Best,

Upvotes: 0

Views: 398

Answers (1)

rayryeng
rayryeng

Reputation: 104535

IIRC, you cannot assign to a containers.Map inside a parfor because a containers.Map is not sliceable. If you want to assign elements to an array inside a parfor, it must be sliceable. What I mean by sliceable is that you are able to extract a subset of the values via the colon operator (i.e. 1:3, 2:4), etc. You cannot do that with a containers.Map unless you specifically use the values function, and from there you can specify a cell array of keys and get the values from there. Using () syntax only permits you to access one key at a time.

Therefore, what I would suggest you do is assign the outputs to a cell array, and use this cell array as values into your containers.Map. Something like this:

%// Create temporary cell array of values
c = cell(1,8);

%// Run parfor for each col
parfor col = 1:8
    c{col} = SpreadFinder(pp, 0.8, i_ranges(:,col)');
end

%// Make a new containers.Map for these values
m = containers.Map(1:8, c, 'uniformvalues', false);
%clear c; %// Optional if you don't want the temporary cell array to stick around

Upvotes: 1

Related Questions