Matlab → Graphs → Plotting a Function

Two vectors x and y are needed to plot a two dimensional graph of a function `y=f(x)`

where x is domain of the function while y is the range of the function. The graph is plotted using the `plot(x,y)`

command.

**Examples**

**1.** Plot a graph for the function `y=sin(x)`

from 0 to 720 degrees.

`>> x=0:720;`

>> y=sind(x);

>> plot(x,y)

**2.** Plot a graph for the function `y=sin(x)`

from 0 to 720 degrees with step size of 30 degree.

`>> x=0:30:720;`

>> y=3*cosd(2*x);

>> plot(x,y,'r-.o')

**Plotting multiple graphs in the same plot**

In the same way, multiple graphs can also be plotted in the single plot. For example, the graphs of `sin(x)`

and `cos(x)`

from 0 degree to 1080 degrees can be plotted as,

`>> x=0:1080;`

>> y=sind(x);

>> z=cosd(x);

>> plot(x,y,'b',x,z,'--r')

In the first graph, the domain x is on the x-axis and the range of the function `sin(x)`

denoted by y is on the y-axis. And in the second graph the domain x is again on the x-axis and the range of the function `cos(x)`

denoted by z is on the y-axis.

**The hold on and hold off commands**

Multiple graphs can also be plotted using hold on and hold off commands. The first graph is plotted using the plot command then the hold on command is typed. After this, other graphs are plotted.The hold on command allows other graphs to be plotted in the same Figure Window. And in the end, hold off command is typed that stops this process and returns Matlab to the default mode where the previous graph is updated with the new graph.

In the next example, we plot three graphs on the same plot where y is a function, and y1 and y2 are its first and second derivatives respectively. The domain of the functions [-4,4] with step size of 0.01. Consider the function,

`>> x=[-4:0.01:4];`

>> y=4*x.^3-2*x.^2-24*x+17;

>> y1=12*x.^2-4*x-24;

>> y2=24*x-4;

>> plot(x,y,'-b')

>> hold on

>> plot(x,y1,'--r')

>> plot(x,y2,':g')

>> hold off