Clear Filters
Clear Filters

Arbitrary sized function evaluation

1 view (last 30 days)
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.

Accepted Answer

Walter Roberson
Walter Roberson on 3 Nov 2011
xt = num2cell(x);
f(xt{:});

More Answers (1)

Jan
Jan on 3 Nov 2011
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.

Categories

Find more on Particle & Nuclear Physics in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!