Anonymus Function from Input function
Show older comments
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
Answers (1)
Star Strider
on 21 Feb 2016
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 Comments
Jose Trevino
on 21 Feb 2016
Star Strider
on 22 Feb 2016
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
on 22 Feb 2016
Star Strider
on 22 Feb 2016
My pleasure!
If my Answer solved your problem, please Accept it.
Categories
Find more on Function Creation 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!