Arbitrary sized function evaluation

2 次查看(过去 30 天)
x is an n-dimensional vector, and f is a function which takes in n variables. Is there a way to dynamically evaluate f so that the number of variables does need to be pre-specified? For example, I would like a single piece of code where if n equal three, would give me f(x(1), x(2), x(3)), and if n = 4, would give me f(x(1), x(2), x(3), x(4)). Any help on this matter would be greatly appreciated.

采纳的回答

Walter Roberson
Walter Roberson 2011-11-3
xt = num2cell(x);
f(xt{:});

更多回答(1 个)

Jan
Jan 2011-11-3
This calls the function f with n scalar elements:
a = 1:4;
c = mat2cell(a, 1, ones(1, length(a)));
y = f(c{:});
Usually it is easier to let the function handle a vector as input. See e.g. sin:
y = sin(1:4)
Then y is a vector also. -Yes, I know this is trivial. But sometimes a programming problem is such impressing, that the programmer forgets the basics.

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by