## Basic plotting tutorial

August 01, 2011 at 06:50 PM | categories: basic matlab, plotting | View Comments

# Basic plotting tutorial

## Contents

it is a good idea to add these lines to the top of your m-files

close all % close all figure windows that are open clear all % clear all the variables currently stored in memory clc % clear the commands in the command window % Plotting functions in Matlab % This m-file describes some very basic ways to plot functions in Matlab.

## ezplot with functions described as strings

you can quickly plot a function of one variable with the ezplot command.

ezplot('x^3 - x^2 +x -1') xlabel('x') ylabel('f(x)')

## plotting two functions with ezplot

if you try to plot another function, you will see the first function disappear. We have to tell Matlab what do with the hold command

figure hold on ezplot('x^3 - x^2 + x -1') ezplot('-x^3 + x^2 - x + 1') hold off % Note that you cannot easily tell which graph is which because the two % lines are the same color. Lets change the color and style of the first % plot to be red and dashed, and add a legend so we can see which line is % which. We do that by saving a reference to each figure in a variable so % we can use the set function to modify each graph. figure hold on h1 = ezplot('x^3 - x^2 + x -1'); h2 = ezplot('-x^3 + x^2 - x + 1'); hold off set(h1,'color','r','linestyle','--') legend('function 1','function2')

## defining and plotting functions

strings are not always convenient to plot, especially if there are a lot of numbers in the equations, or if there are multiple variables. Let's plot the van der Waal's equation of state to show this.

where a and b are constants. This equation cannot be plotted as a string like we did in the examples above. Instead, we need to define a function. Our goal is to find where this function is equal to zero. We can do that graphically.

% numerical values of the constants a = 3.49e4; b = 1.45; p = 679.7; T = 683; n = 1.136; R = 10.73; % we define a function handle that is f(V) f = @(V) V.^3 - (p*n*b+n*R*T)/p*V.^2 + n^2*a/p*V - n^3*a*b/p; figure ezplot(f) %the large scale of the y-axis makes it difficult to see where the function %is equal to zero, so we change the limits of each axis. xlim([2 6]) ylim([-5 5]) xlabel('Volume') ylabel('f(V)')

```
%it appears that f(V) = 0 around V=5
f(4.9)
f(5.1)
```

ans = -0.4486 ans = 0.0145

we can add these two points to the figure with the plot command. Here we add them as red circles.

hold on plot(4.9,f(4.9),'ro') plot(5.1,f(5.1),'ro') hold off % The zero is definitely between V=4.9 and V = 5.1 because f changes sign % between these two points.

```
%alternatively, we could tell ezplot to plot f from x=4 to x=6 like this
figure
ezplot(f,[4 6])
```

% categories: Basic Matlab, Plotting % post_id = 625; %delete this line to force new post;