Matlab_04a
Simple Graphs
We will start with an easy one, the graph of x squared between -5 and +5:
x = [-5 -4 -3 -2 -1 0 1 2 3 4 5];
y_1 = x.*x; % or x.^2 will also work
plot(x,y_1)
Note that the first line can be expressed in the shorthand:
x = [-5:5];
y_1 = x.*x;
plot(x,y_1)
or to get a graph with more points in the same range we can add the step size to the first line, this goes between the lower and upper value in the range:
x = [-5:0.1:5];
y_1 = x.*x;
plot(x,y_1)
To plot more than one line on the same graph:
x = [-5:0.1:5];
y_1 = x.*x; % this gives us x squared
y_2 = x.*x.*x; % this gives us x cubed
plot(x,y_1) % plot the x squared graph
hold on; % hold the plot for a second line
plot(x,y_2) % plot x cubed
The trick is the hold on
command which holds the same figure open for extra plots. Note that I have added comments (after the percentage signs) which explain what each line does. Anything that comes after a percent sign on the line is ignored by Matlab when it executes instructions.
You can easily add colours to the lines by using r,g,b,c,m,y,k in the plot commands like this:
x = [-5:0.1:5];
y_1 = x.*x; % this gives us x squared
y_2 = x.*x.*x; % this gives us x cubed
plot(x,y_1,'r') % plot the x squared graph
hold on; % hold the plot for a second line
plot(x,y_2,'g') % plot x cubed