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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With