当数组的每一行都是输入时,arrayfun [英] arrayfun when each row of the array is an input

查看:84
本文介绍了当数组的每一行都是输入时,arrayfun的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况是,我想通过带有句柄fun的函数映射标量数组A,该函数将行向量发送到行向量,以获取B,例如B(i,:) = fun(A(i,:)).

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));

但是,转换为单元格和返回单元格似乎是过大的(并且在计算上可能是昂贵的).我也不清楚为什么cellfun抱怨输出不均匀.是否会想到一种更有效的方法?

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?

推荐答案

还有另一种采用 accumarray .尽管不如bsxfun花哨,但它不需要声明辅助函数:

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

这篇关于当数组的每一行都是输入时,arrayfun的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆