playground_06_plotting - VMinhoto/workshop-matlab GitHub Wiki

Plotting

2D Plot

Plotting in Matlab is extremely easy. There are three steps:

  • Define x, by specifying the range of values for the variable x, for which the function is to be plotted.
  • Define the function, y = f(x)
  • Call the plot command, as plot(x, y)
%Plot the x^2 function from -100 to 100
x = [-100:5:100];
y = x.^2;
plot(x, y);

The more points you have, the smoother the plot will be.

Getting fancy

Matlab allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.

  • The xlabel and ylabel commands generate labels along x-axis and y-axis.
  • The title command allows you to put a title on the graph.
  • The grid on command allows you to put the grid lines on the graph.
  • The axis equal command allows generating the plot with the same scale factors and the spaces on both axes.
  • The axis square command generates a square plot.
%Plotting the sine function with fancy stuff
x = [0:0.01:10];
y = sin(x);
figure(1);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal

%Plot 2 functions on same graph
figure(2)
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')

3D Plot

Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y).

As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot.

[x,y] = meshgrid(-2:.2:2);
g = x .* exp(-x.^2 - y.^2);
surf(x, y, g);
colormap(jet); %Pretty colors :)