How to pass a matrix back using arrayfun?

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일

0 개 추천

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일

0 개 추천

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{:}];

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2015년 9월 9일

답변:

2015년 9월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by