MATLAB Answers

How can I plot a sin (x^2) function

179 views (last 30 days)
here is my code and it works but the figure is obviously not a sin(x^2) function from -pi to pi
syms x;
f=@(x)sin(x.^2);
x=[-pi pi];plot(x,f(x))
grid

  0 Comments

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 17 Sep 2019
Edited: John D'Errico on 17 Sep 2019
First, there is ABSOLUTELY NO reason to predefine x as a sym. So this line is completely irrelevant:
syms x;
When you do create x, you overwrite the symbolic version of x that you created before anyway.
Next, you created a function
f=@(x)sin(x.^2);
Good there. But then what?
What do you think this does?
x=[-pi pi];
It does NOT create the interval [-pi,pi]. Instead, it creates a vector of length 2, so TWO values, -pi and pi. Then when you plotted, using
plot(x,f(x))
it plots TWO points, connected with a straight line. And since the two poiints each had function value of zero, the line is perfectly horizontal. Compare that to this version:
f=@(x)sin(x.^2);
x=linspace(-pi,pi,100);
plot(x,f(x))
grid
See that I never needed to pre-define x as symbolic. (Why would you want to do that anyway? Just because you don't know the value of something, does not mean it must automatically be symbolic. This is perhaps the one of most common mistakes I see made by new users.)
Simpler yet, you might have done just this:
f = @(x) sin(x.^2);
fplot(f,[-pi,pi])
grid

  1 Comment

Drew Levis
Drew Levis on 17 Sep 2019
I appericate the help. I started to think and come to a simlar answer when looking at the figure again. I am glad my thoughts were confirmed. THANK YOU again.

Sign in to comment.

More Answers (2)

madhan ravi
madhan ravi on 17 Sep 2019
fplot(@(x)sin(x.^2),[-pi,pi])

  1 Comment

Sign in to comment.


Navadeep Ganesh U
Navadeep Ganesh U on 30 Nov 2019
f=@(x)sin(x.^2);
x=linspace(-pi,pi,100);
plot(x,f(x))
grid

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags

Products