Effacer les filtres
Effacer les filtres

Arbitrary sized function evaluation

1 vue (au cours des 30 derniers jours)
Daniel Wells
Daniel Wells le 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.

Réponse acceptée

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

Plus de réponses (1)

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

Catégories

En savoir plus sur Particle & Nuclear Physics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by