Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arrayfun when each row of the array is an input

Tags:

matlab

My situation is that I would like to map a scalar array A by a function with handle fun sending a row vector to a row vector, to acquire B, such that B(i,:) = fun(A(i,:)).

The most reasonable solution I could think of looks like:

temp = mat2cell(A,ones(1,size(A,1)),size(A,2));
B = cell2mat(cellfun(fun,temp,'UniformOutput',0));

However, the conversion to cells and back seems like overkill (and is assumably computationally expensive). It is also not clear to me why cellfun complains about non-uniform output. Does a more efficient way jump to mind?

like image 466
Eugene Shvarts Avatar asked Aug 13 '13 02:08

Eugene Shvarts


1 Answers

There's another solution that employs accumarray. Although not as fancy as bsxfun, it doesn't require declaring a helper function:

subs = ndgrid(1:size(A, 1));
B = accumarray(subs(:), A(:), [], @fun); %// @fun is the function handle
like image 62
Eitan T Avatar answered Sep 19 '22 12:09

Eitan T