Plotting

Contents

Basic plotting commands

The MATLAB "plot" command is the basis for most two-dimensional plotting and visualization tasks in MATLAB. If you provide a vector of data, the plot will index your values as 1, 2, 3, ...

y = [1:.5:4].^2
plot(y)
y =

    1.0000    2.2500    4.0000    6.2500    9.0000   12.2500   16.0000

Basic plotting commands example

Back to top

Specify domain values

In this example, the domain values are not 1, 2, 3, ... but rather are spaced by 0.5. Once x is defined, the definition of y can be done in terms of x.

x = [1:.5:4]
y = x.^2
x =

    1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000


y =

    1.0000    2.2500    4.0000    6.2500    9.0000   12.2500   16.0000

Back to top

Plot

plot(x, y)

Plot example

Back to top

Another example and plotting options

This example looks at the function:

y = xsin(x^2)

The @ operator turns an expression in a variable into a function that takes the variable as its operand. Note: This is not supported in older versions of MATLAB.

x = -10:0.001:10;
f = @(x) x.*sin(x.^2);
y = f(x);
plot(x,y);

y=xsin(x^2) example

Back to top

Adjust axes

axis([-5 5 -4 4])

Adjust axes example

Back to top

Add a legend, title, and axis labels

legend('y = x sin(x^2)') 
title('My Plot') 
xlabel('x') 
ylabel('x sin(x^2)')

Add a legend, title, and axis labels example

Back to top

Add a grid and a box around the whole plot

grid on
box on

Add a grid and a box around the whole plot example

Back to top


Published with MATLAB® 7.4