Borrar filtros
Borrar filtros

Arbitrary sized function evaluation

1 visualización (últimos 30 días)
Daniel Wells
Daniel Wells el 3 de Nov. de 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.

Respuesta aceptada

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

Más respuestas (1)

Jan
Jan el 3 de Nov. de 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.

Categorías

Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by