Borrar filtros
Borrar filtros

How to extract functions from a vector of functions

1 visualización (últimos 30 días)
Louis
Louis el 12 de Jul. de 2018
Comentada: madhan ravi el 30 de Ag. de 2018
I have a set of functions in a vector form, and I am hoping to find a way to extract each individual function in an automated way. Below are the functions
f = @(x)[1; x; cos(2.*pi.*x); sin(2.*pi.*x); exp(-x)]
How would I be able to generate functions that access the entries in f(x)? Any and all help would be greatly appreciated. Thanks!
  2 comentarios
Walter Roberson
Walter Roberson el 12 de Jul. de 2018
Do you have the symbolic toolbox?
When the functions are generated, is it acceptable to assume that the generated functions only need to work with scalar inputs? For example that code for f would fail with row vector x but would succeed with column vector x.
Louis
Louis el 13 de Jul. de 2018
I do have the symbolic toolbox. However I would like to have each extracted function as a function handle. The reason is because I would like to do a fair amount of numerical integration and nonlinear equation solving with each individual entry in f. Please let me know if you need more clarification.

Iniciar sesión para comentar.

Respuestas (1)

Walter Roberson
Walter Roberson el 30 de Ag. de 2018
With the symbolic toolbox, you would
syms x
Fh = arrayfun(@(s) matlabFunction(s, 'vars', x), f(x), 'uniform', 0);
Well, not quite. Really you have to loop over the expressions that result from f(x), and you have to test each one to see if x is present in it's symvar. If it is present then you matlabFunction and store the handle. If it is not present then you have to construct an anonymous function that takes a variable x as the argument and returns ones(size(x)).*Y where Y was the expression returned in that component of f(x)
To phrase this another way: your f includes components that do not vary in size according to the size of x, such as the 1 at the beginning of it. When you matlabFunction() a constant value such as that 1, then matlabFunction just returns a single copy of the constant no matter what the input size is. And that is a problem for integral() and various other routines which require that the size of the output is the same as the size of the input. Therefore when you detect an expression that is constant you need to interpose a function that makes as many copies of the constant as needed to match the input.
In the situation where you know that none of the components are constants then the arrayfun matlabFunction is fine. (At least since about R2015b. In earlier releases, arrayfun could not always operate on symbolic arrays.)

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by