Filter löschen
Filter löschen

Arbitrary sized function evaluation

1 Ansicht (letzte 30 Tage)
Daniel Wells
Daniel Wells am 3 Nov. 2011
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.

Akzeptierte Antwort

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

Weitere Antworten (1)

Jan
Jan am 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.

Kategorien

Mehr zu Particle & Nuclear Physics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by