Passing array arguments to an anonymous function

7 ビュー (過去 30 日間)
Leo Simon
Leo Simon 2013 年 2 月 26 日
I have an anonymous function, for example
f = @(x,y)x.^2.*y.^2
In general for my problem I don't know how many arguments f will have. Nor do I know how many elements each argument will have.
I want to pass in a single element as an argument. If x and y are scalars, I can define z = num2cell(x,y), then write
f(z{:})
But if x and y are vectors this doesn't work. I could write
for ii=1:2; z = { x(ii);y(ii) }; f(z{:}) ;end
but of course I want to avoid the loop.
Is there some efficient way to obtain what I want by writing something like
f(q{:})
where q{:} is a cell array with each cell containing a vector rather than a scalar.
  1 件のコメント
Walter Roberson
Walter Roberson 2013 年 2 月 26 日
num2cell(x,y) is not the same thing as {x,y} when x and y are scalars. Instead num2cell(x,y) says to use y as the dimension number for the num2cell(x) operation.

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2013 年 2 月 26 日
It appears to me that what you want is arrayfun:
arrayfun(f, x, y)
  1 件のコメント
Leo Simon
Leo Simon 2013 年 2 月 26 日
Thanks Walter, this is really helpful. For the benefit of anybody else reading, I'm expanding on your answer, to deal with my problem in which the function f has a variablenumber of arguments.
In my case, f could be
f = @(x1,x2,x3)[ prod(x1*x2*x3);prod(x1*x2*x3)]
or
f = @(x1,x2,x3,x4)[prod(x1*x2*x3*x4);prod(x1*x2*x3*x4)];
where the xi's could be scalars or row vectors.
I want to be able to input a single argument that works for both.
The following works:
X = rand(4,3);
Z = {};for ii=1:size(X,2); Z = [ Z , X(:,ii) ] ; end
arrayfun(f,Z{:},'UniformOutput',false)
The third and fourth arguments appear to be needed because f is vector valued.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by