MATLAB: Running function on GPU for all combination of variables

carlogpumontemontecarloparallel

Hi!
I'd like to run a highly-parallel simulation, taking advantage of my GPU.
Basically, i have a function that outputs a scalar, that takes as input other six variables. I want to run this function for all the combination of the variables, like this:
v1 = linspace(v1a,v1b,N);
v2 = linspace(v2a,v2b,N);
v3 = linspace(v3a,v3b,N);
v4 = linspace(v4a,v4b,N);
v5 = linspace(v5a,v5b,N);
v6 = linspace(v6a,v6b,N);
R = [];
for i1 = 1:N
for i2 = 1:N
for i3 = 1:N
for i4 = 1:N
for i5 = 1:N
for i6 = 1:N
r = myfun(v1(i1),v2(i2),v3(i3),v4(i4),v5(i5),v6(i6));
R = [R; r];
end
end
end
end
end
end
In this case, I'd use parfor to descrease the simulation duration, but the size of this variable is quite large so I'd prefer to run the simulation on the GPU.
I read about arrayfun, but its outcome would be R(i) = myfun(v1(i),…,v6(i)) , so it wouldn't run all the combinations, obtaining N results instead of N^6.
How could I write it in an efficient way? I guess it's a bad idea to create the grids before the call of the function, it would occupy too much memory…
Thank you very much.

Best Answer

In this case, I'd use parfor to descrease the simulation duration, but the size of this variable is quite large so I'd prefer to run the simulation on the GPU.
No, if your myfun is completely generic, then parfor would be better.
R=nan(N^6,1); %pre-allocate
parfor n=1:numel(R)
[i1,i2,i3,i4,i5,i6]=ind2sub([N,N,N,N,N,N] ,n);
R(n) = myfun(v1(i1),v2(i2),v3(i3),v4(i4),v5(i5),v6(i6));
end
However, further optimization may be possible depending on the particulars of hat myfun is doing.