How to pass a matrix back using arrayfun?

3 views (last 30 days)
Philip
Philip on 9 Sep 2015
Answered: Joss Knight on 9 Sep 2015
I have a function that performs a lot of element wise operations and returns numerous output. An example is
A = myfun(B)
where A is [1xn] and B is [1xm]. I have to use this function numerous times in parallel. I would like to accelerate this function using a GPU and arrayfun. To do this, I would have to call
[A1,...,An] = arrayfun(myfun,B1,...,Bm); where each matrix has the same number of rows (assume j). However, in my case n=30, and I want to use the output of arrayfun after calling it. Is there a way to have arrayfun return A, where A is one matrix of size [jxn]? This would save me a lot of hassle of having to: 1. Code [A1,...,A30] = arrayfun(); 2. Collect the code A = [A1 ... A30];
Really this question is more about convenience (but I suspect creating 30 individual vectors as opposed to one matrix could also impose a performance penalty). Thank you for your help.

Answers (2)

Walter Roberson
Walter Roberson on 9 Sep 2015
arrayfun(myfun,B1,...,Bm, 'Uniform', 0)
  1 Comment
Philip
Philip on 9 Sep 2015
Thanks for the suggestion, but MATLAB does not accept 'Uniform' parameter when executing arrayfun on GPUs.

Sign in to comment.


Joss Knight
Joss Knight on 9 Sep 2015
If myfun is a function that takes in m values and, using all of them, computes n values, then it is a vector function. arrayfun is not appropriate here, since it needs to be a scalar function, processing scalar values and outputting scalar values. Hence your need to call it the way you describe. This parallelizes over the variable which is truly independent between threads - j - rather than over m or n which seem to be dependent (you need all m values from a row of B to generate all n values for a row of A, which means every thread will need read access to all m Bs and write access to all n As).
If this is merely about a matter of convenience, convert your jxm matrix B into a cell array with one column per cell (using mat2cell), and collect your output A using cell indexing syntax:
Bcell = mat2cell(B, j, ones(1,m));
Acell = cell(1,n);
[Acell{1:n}] = arrayfun(@myfun, Bcell{:});
A = [Acell{:}];

Community Treasure Hunt

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

Start Hunting!