How to pass a matrix back using arrayfun?
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
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{:}];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 GPU Computing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!