Treat a function like a variable
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Star Strider
2015-10-7
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 个评论
Star Strider
2015-10-8
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!