How to pass a matrix back using arrayfun?

10 ビュー (過去 30 日間)
Philip
Philip 2015 年 9 月 9 日
回答済み: Joss Knight 2015 年 9 月 9 日
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.

回答 (2 件)

Walter Roberson
Walter Roberson 2015 年 9 月 9 日
arrayfun(myfun,B1,...,Bm, 'Uniform', 0)
  1 件のコメント
Philip
Philip 2015 年 9 月 9 日
Thanks for the suggestion, but MATLAB does not accept 'Uniform' parameter when executing arrayfun on GPUs.

サインインしてコメントする。


Joss Knight
Joss Knight 2015 年 9 月 9 日
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{:}];

カテゴリ

Help Center および File ExchangeGPU Computing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by