How to plot a linear approximation next to a function?

Hey,
I have a function
f=@(x)0.5*(x-2).^2-2*cos(2*x)-1.5;
And I want next to the function f(x) to plot:
f(-1)+f'(-1)(x-(-1))
where f'(x)=x+4sin(2x)-2
How do I go about this?
I tried making a function file
function y=linjar(a)
a=-1;
f(a)=0.5*(a-2).^2-2*cos(2*a)-1.5
dy(a)=a+4*sin(2*a)-2;
y=f(a)+dy(a)*(x-a);
and then calling the function out on another script with
f=@(x)0.5*(x-2).^2-2*cos(2*x)-1.5;
x=linspace(-3,7);
plot(x,f(x))
axis([-3 7 -5 10]), grid on
hold on
plot(a,linjar(a,-1))
and I get the message: Error using linjar Too many input arguments.
I'm new to Matlab so ANY ideas where to start are welcomed.

 Accepted Answer

As you wrote your ‘linjar’ function originally, it only takes one argument. In the line that’s throwing the error, you gave it two.
It would seem that what you want is actually:
function y=linjar(a,x)
f = @(a) 0.5*(a-2).^2-2*cos(2*a)-1.5;
dy = @(a) a+4*sin(2*a)-2;
y=f(a)+dy(a)*(x-a);
creating anonymous functions where you seem to want them, adding ‘x’ as an argument (because it will throw an error if ‘x’ is not defined somewhere), and eliminating the ‘a=-1;’ line because that would override the value of ‘a’ you provided as an argument.
I don’t understand the (-1) references. If you mean the value (-1), enter it as an argument. If you mean the inverse of your function, that requires a bit more code.

5 Comments

Thank you for replying!
What I want with the (-1):
I want to plot f(x) and it's linear approximation at a=-1 from the definition of linearization L(x)=f(a)+f'(a)(x-a) which is in matlab code
y=f(a)+dy(a)*(x-a);
Too simplify more. I want the graph of f(x) and the graph of f(-1)+f'(-1)(x-(-1)) all in the same place. Do you understand?
I tried your correction with
plot(a,linjar(a,-1))
and I still get to many input arguments.
Should I use subfunctions?
My pleasure!
Now I understand about -1.
Be sure you copy the first line of my ‘linjar’ function as well:
function y=linjar(a,x)
When I just now ran the same code I posted, it worked fine for me.
okay I ran the code and now finally the code works! Thank you again for helping me. It's so frustrating getting stuck on a task and you can't move forward. You need someones output if only to get you thinking in another way.
hugs
My pleasure!
I’ve definitely been there myself!
Thank you! And have fun with your Chemistry studies. (My undergrad major was Chemistry.)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!