Treat a function like a variable

4 visualizaciones (últimos 30 días)
Mark Oler
Mark Oler el 7 de Oct. de 2015
Comentada: Star Strider el 8 de Oct. de 2015
Hi there, the question seems vague so allow me to expand.
I have a function that is a simple equation with an input of 'x'. I wish to put this through a loop and multiply it again by 'x' (this would give me: 1) fun(x), 2) fun(x)*x, 3) fun(x)*x*x etc..) I cannot figure out a way to do this as I can't pass the variable 'x' to the outside loop in order to tell Matlab it is a "new" function with respect to its 'x' input.
Now this seems super easy when it is algebra on paper, but Matlab doesn't seem to treat 'x' as an unknown and just work with it until I specify the value.
How can a person take a function (of x) and multiply it by another function (of x) to create a third function, allowing this to be performed by a loop.

Respuestas (2)

Star Strider
Star Strider el 7 de Oct. de 2015
I may not understand what you’re describing, but this works:
f = @(x) x.^2;
for k1 = 1:5;
g(k1) = k1*f(k1);
end
g =
1 8 27 64 125
  2 comentarios
Mark Oler
Mark Oler el 8 de Oct. de 2015
This is close to what I need, but k1 shouldn't be a simple number, I need to multiply by another function of x. So I guess can I multiply multiple anonymous functions?
Star Strider
Star Strider el 8 de Oct. de 2015
You definitely can multiply anonymous functions (just not function handles):
f = @(x) x.^2;
g = @(x) x + sin(x);
x = linspace(-pi, pi, 6);
for k1 = 1:length(x);
r(k1) = f(x(k1)) .* g(x(k1));
end
r
r =
-31.006 -10.077 -0.4801 0.4801 10.077 31.006
If you want to, you could dispense with the loop entirely and simply do element-wise vectorised multiplication:
r = f(x) .* g(x)
produces the same result.

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 8 de Oct. de 2015
f= @(x) x + 1;
for k1 = 1 : 5
f = @(x) x * f(x);
end
f(2)

Categorías

Más información sobre Loops and Conditional Statements 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