Treat a function like a variable

조회 수: 4 (최근 30일)
Mark Oler
Mark Oler 2015년 10월 7일
댓글: Star Strider 2015년 10월 8일
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.

답변 (2개)

Star Strider
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
Mark Oler
Mark Oler 2015년 10월 8일
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 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.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2015년 10월 8일
f= @(x) x + 1;
for k1 = 1 : 5
f = @(x) x * f(x);
end
f(2)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by