How to plot a linear approximation next to a function?

조회 수: 5 (최근 30일)
Britney
Britney 2014년 10월 9일
댓글: Star Strider 2014년 10월 9일
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에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by