How to pass on a different sized matrix through GPU Arrayfun

I wrote the following program:
x1 = parallel.gpu.GPUArray.linspace(low,high,N)';
x2 = parallel.gpu.GPUArray.linspace(low,high,N)';
[xx1,xx2] = ndgrid(x1,x2);
[y1,y2] = arrayfun(@fun, xx1,xx2, Vmatrix, constant);
I want y1 and y2 to be output whose elements corresponding to each element of xx1 and xx2. But in order to calculate each element of y1 and y2 I also need to use Vmatrix which is a matrix.
In order to pass on Vmatrix that is a different size from matrix xx1, can I define the following?
Vcell=cell(size(xx1));
and for each cell element=Vmatrix. In this way the Vcell will have the same dim of xx1 and xx2, and write:
[y1,y2] = arrayfun(@fun, xx1,xx2, Vcell, constant);
Thank you!

Answers (1)

Unfortunately, you cannot pass cell arrays to the GPU. What you might be able to do is instead use a nested function handle to pass in your matrix through the "up-level workspace". Here's an example:
function example
% Define a matrix and a vector
matrix = magic(5);
gpuVector = gpuArray.colon(1, 10);
% Nested function definition for use with arrayfun
% which accesses "matrix"
function out = nestedFcn(in)
out = in;
for i = 1:5
for j = 1:5
% Remember we must use only scalar operations
% within arrayfun on the GPU
out = out + matrix(i, j);
end
end
end
% Call arrayfun.
arrayfun(@nestedFcn, gpuVector)
end

2 Comments

Thank you Edric, that's a brilliant idea. I thought it is going to work as well, but just now I tried, it has this error message:
Error using gpuArray/arrayfun Use of 'arrayfun' is not supported.
The error appears at code line: [V, P] = arrayfun(@nestfun, n1); where n1 is a 5*5*5 GPU array, V P are undefined output.
Have you tried passing on variables in this setting for GPU arrayfun before? If it worked back then, I must have done something wrong here?
Thanks a lot!
I figured out this error, it was because I had two layers of nested functions each with an arrayfun. When I use one layer of nested function, it is fine. But a new error I got is "Use of 'colon' is not supported" or "indexing is not supported" (but it worked in your example above), regardless of the variable class in CPU or GPU.
I need to use some matrix or vector-wise operations because the matrix is passed on to be part of the inputs for interpolation and matrix multiplication. For the interpolation in 3D, I am doing it in a self defined function that calls a CUDA C code (which I tested to be working). Is that a possible cause for the errors in nestedfun with GPU arrayfun?
Thanks!

Sign in to comment.

Asked:

on 5 Nov 2013

Commented:

on 7 Nov 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!