Which one is correct ? Using (' ') or @(var)
Show older comments
I found that using (' ') can result in the same value on feval(), or other functions like fplot(), instead of using @(x). What is the difference? Also I read documentation and inline(expr) works too, even though it's rather not recommended. For example :
feval('sin',[pi/2,pi])
%or
fplot('2*x^3+2.*cos(2*x).*sin(2*x)+3.*tan(2*x)',[-5 5], '--r')
%or example for @()
feval(@(x) sin(x),[pi/2,pi])
fplot(@(x) 2*x^3+2.*cos(2*x).*sin(2*x)+3.*tan(2*x),[-5 5], '--r')
2 Comments
Image Analyst
on 8 Nov 2021
Edited: Image Analyst
on 8 Nov 2021
I don't understand the question. Where are you using either '' or @????
Exactly what is not recommended? Reading the documentation . . . or some particular function like feval() or fplot()?
Aji Bowo
on 8 Nov 2021
Accepted Answer
More Answers (1)
Some older functions allow you to specify the name of a function to call. But if you're writing code to use in a recent release of MATLAB, prefer using an anonymous function or a regular function handle.
Don't use inline objects either. Those are very old and have some idiosyncracies that function handles or anonymous functions don't. For instance, composing anonymous functions is easy. Composing inline objects is most certainly not.
f = @(x) 2*x;
g = @(x) x.^2;
h = @(x) f(g(x)); % 2*x.^2
h(5) % 2*5.^2 = 50
f2 = inline('2.*x', 'x');
g2 = inline('x.^2', 'x');
h2 = inline('f(g(x))', 'f', 'g', 'x')
h2(f2, g2, 5) % Yes, you have to pass f2 and g2 into h2
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!