How to plot a linear approximation next to a function?

5 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2014-10-9
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 个评论
Britney
Britney 2014-10-9
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
Star Strider
Star Strider 2014-10-9
My pleasure!
I’ve definitely been there myself!
Thank you! And have fun with your Chemistry studies. (My undergrad major was Chemistry.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Chemistry 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by