Treat a function like a variable
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponses (2)
Star Strider
le 7 Oct 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 commentaires
Star Strider
le 8 Oct 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.
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!