Anonymus Function from Input function
显示 更早的评论
Hi, I am writing a code that takes an input function (f) and then the code does some operations with it. It was using inline function but I prefer to use anonymous function. It was set as f1=inline(f); In order to use the anonymous instead of inline, I changed it to f1 = @(x)[f]; However, after declaring it like this, the code stops working correctly. I don't know what I'm doing wrong.
Thank you
回答(1 个)
Star Strider
2016-2-21
you have to call the inline function as a function.
This works:
f = inline('cos(x) .* sin(x)');
f1 = @(x) f(x);
q = f1(pi/4);
Better is to just do:
f1 = @(x) cos(x) .* sin(x);
4 个评论
Jose Trevino
2016-2-21
Star Strider
2016-2-22
You need to rename and restate the secondary functions, and then change the other references to them in your code:
F = @(x)f(x);
DF = @(x)df(x);
Since MATLAB is case-sensitive, it won’t get confused.
However, you really don’t need to do all that. Something like this will work as well:
f = inline('sin(x) .* cos(x)');
deriv = @(f,x) (f(x+1E-8) -f(x))./1E-8; % Simple Numerical Derivative
x = linspace(0, 2*pi);
figure(1)
plot(x, f(x))
hold on
plot(x, deriv(f,x))
hold off
grid
This is just an illustration. If your functions are function files, you will have to pass them as function handles:
function [ r, error ] = newton( @f, @df, x0, tol, N )
Note the preceding ‘@’ sign, creating the function handles for ‘f’ and ‘df’.
Jose Trevino
2016-2-22
Star Strider
2016-2-22
My pleasure!
If my Answer solved your problem, please Accept it.
类别
在 帮助中心 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!