Treat a function like a variable

5 views (last 30 days)
Mark Oler
Mark Oler on 7 Oct 2015
Commented: Star Strider on 8 Oct 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.

Answers (2)

Star Strider
Star Strider on 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 Comments
Mark Oler
Mark Oler on 8 Oct 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 on 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.

Sign in to comment.


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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!