Cell arrays in MATLAB using parfor

1.3k views Asked by At

I need to parallelize a script in MATLAB. I have a cell array that I am returning values to. But, MATLAB does not accept the way that I structure the parallelization of my script.

N_h = 4;
N_r = 6;
N_s = 20;

P{1:N_h, 1} = zeros(N_s, N_r);

workers = 4;                                % number of cores (workers) for parallel computing 
multicore = parpool('local', workers);      % open multiple workers (cores) for parallel computation 

for h = 1:1:N_h
    for r = 1:1:N_r
        parfor s = 1:N_s
            P{h,1}(s,r) = some function ... 
        end
    end
end

delete(multicore);                      % delete multiple workers (cores) opened for parallel computation

MATLAB responds that the variable P is indexed in a way that is incompatible with parfor. How should I change my script?

1

There are 1 answers

0
rlbond On

The easiest way to do this is to create a temporary vector, store the parallel results there, and then assign the values all at once.

for h = 1:1:N_h
    for r = 1:1:N_r
        svec = zeros(N_s, 1);
        parfor s = 1:N_s
            svec(s) = my_very_parallelizable_func(param1, param2);
        end
        P{h,1}(:,r) = svec;
    end
end