Plotting functions and curvesLast revision: May 10, 2016
Plotting mathematical objects is both useful and beautiful. Today we will just scratch the surface of the vast area of mathematical computer graphics, but we hope to give you a hint of what it looks like.
As our first task, we will try to plot a function. Imagine that you don’t know any maths, but you have a powerful calculator. How do you plot a function? You make up a table with a lot of points, and put all those points in a graph. OK, let us have a try. Let’s say we want to plot the $f(x)=\sin(x)$ function.
Remember how to generate all $x$ values from 0 to 10 at once?
That’s right, you just do
x=0:10;. Now, you want to
compute the sine of all those values and put the numbers on another
vector. So, you do:
y=sin(x);. Next, you
Octave the command to plot the result:
Of course, the command
plot, takes two arguments: the
x values and the vector of
values, and plots them. But you can see that the plot is quite coarse
and ugly. How to improve them? Right: give more points!!
0:0.1:10 means all numbers from 0 to 10,
with steps of size 0.1, so we get
0, 0.1, 0.2, ...
1, 1.1, 1.2, ... 9.8, 9.9, 10. Thus, many more points.
The plot is much smoother and nice.
You can also do several plots on the same screen very easily:
Remember that some functions require a dot in order to be
properly evaluated for a vector. For example,
1./x. Thus, if we want to
plot $f(x)=1/(1+x^2)$ in the range $x \in [-10,10]$,
we have to do:
plot command is only useful to plot in cartesian
coordinates. But, if we have a vector of $\theta$ values and another
of $R$ values, we can convert them to cartesian coordinates with
our usual expressions:
So, let us try an example. Let’s plot $R(\theta)=\theta $. We will give a wide range for $\theta$, in order to be sure that we catch it all.
Now, for something more beautiful, we can try a polar rose, $R(\theta) = \cos(5\theta/12)$:
- Plot the polynomial $y=1-x^2$ and the gaussian $y=\exp(-x^2)$.
- Draw an ellipse in polar coordinates, with semiaxes $a=2$ and $b=5$.
- A particle follows a trajectory given by the
equations $x(t)=\sin(t)$, $y(t)=\sin(2t)$. Start getting a
vector for your $t$ values, using
t=0:0.1:20;, and use it to get an image of the trajectory.