Using bsxfun instead of arrayfun for repeating function

2 次查看(过去 30 天)
I am using a function that produces row vectors based on the RNG. Now I would like to repeat that function and put the rows into a matrix. I am currently using arrayfun, but that seems inneficient to me. Is there a way to use bsxfun to do this?(I included an example code to show what I mean)
Jos van den Berg
u=4;
v=5;
h=6;
cell2mat(arrayfun(@(i) myfun(v,u,h) , 1:3, 'UniformOutput', false )')
function y = myfun(v,u,h)
y = [u*rand,v*rand,h*rand];
end

采纳的回答

Guillaume
Guillaume 2016-11-29
bsxfun serves a completely different purpose to arrayfun. One rarely replaces the other. Note that as of R2016b, for most operations, bsxfun is not needed anymore.
In your particular example, the whole output could be obtained simply with:
y = [u * rand(3, 1), v * rand(3, 1), h * rand(3, 1)];
or if you really wanted to use bsxfun:
y = bsxfun(@times, [u, v, h], rand(3, 3));
and as said, as of R2016b, the bsxfun can be replaced by implicit expansion:
y = [u, v, h] .* rand(3, 3);
  3 个评论
Guillaume
Guillaume 2016-11-29
bsxfun is only useful, if your unknown function takes exactly two inputs (scalar, vectors, or matrices) and returns one input. It's certainly not designed to repeatedly call a function.
For that, indeed arrayfun or a loop is the way to go. I tend to prefer arrayfun as it makes it clear what is being repeated and what it is repeated over, but an explicit loop can actually be faster as it avoids the cost of calling an anonymous function.
JJP van den Berg
JJP van den Berg 2016-11-29
Not really sure how I got to this misconception of bsxfun. Thanks a lot for the explanation!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by