MATLAB basic guide to create 2D and 3D Plots Part I–Introduction

advertisement
MATLAB basic guide to create 2D and 3D Plots
Part I–Introduction
This guide will walk you through the steps necessary to create, using MATLAB, a Three–dimensional surface,
a Two–dimensional contour plot or a graph combining both. But before getting to that point we need to go
through some basics that will help us getting to the final objective.
First start your MATLAB program, and the window that you will see is similar to the following figure. This is
the MATLAB desktop.
The MATLAB desktop is divided into three windows. To the left you have the Workspace window, here you
will see all the variables you are working with when running a program. Typically by default this window
shows the files in the current directory, click on the tab corresponding to Workspace. Below you will see the
command history window, and the bigger window as seen corresponds to the command window.
Most of the time is necessary to write a program rather than just writing few commands, at least this will be our
situation. Thus under these circumstances it is better to work with the MATLAB editor. To open the editor you
need to click on the first icon shown on the command bar.
Click on this icon to open the editor.
Once you open the editor a new window will open. This is the editor that we will use to write our programs.
Let’s start with a simple program. Since we are going to be creating plots we will start by writing a program to
plot a function such as f (x) = .3x4 – 1.2x3 – 2x2 + 3x. In addition let’s say that we want to create this plot for x ϵ
[- 3; 5] in steps of .05. Copy the text below and paste it to your MATLAB editor, then save the program as
“program1” or give any name you prefer and run it. See figure below program to locate saving and running
icons.
Program 1
clc % clears the command window
clear all %clears all variables from workspace
% Since we want to have x varying from -3 to 5 we can use the following
% instruction that creates a vector with elements going from -3 to 5 in
% increments of 0.05
x = -3:.05:5.5;
% Now we define a variable that will play the role of f(x) let's say y
y = .3*x.^4 - 1.2*x.^3 - 2*x.^2 + 3*x;
% As you can see, since x is a vector when we calculate say x to the power
% 4 we need to do it for each element of the vector x, this is done in
% MATLAB language by putting a period between the variable and the
% operation that needs to be performed.
plot(x,y); % plots in the horizontal axis vector x and in the vertical axis
%vector y
grid on %adds a grid to the plot
Click on this icon to save program.
Click on this icon to execute program.
As you can see, any text written after a percentage sign (%) is understood by MATLAB as a comment and it is
written in green letters.
Now if you go to the MATLAB desktop you will see that all variables that we used in the program are listed in
the workspace window along with all the elements and dimensions of these variables, see the figure below.
As seen, x and y are both vectors with 1 row and 171 columns.
After writing our first program we continue with another programming structure named loop. Loops are
programming structures that are used very often. Loops are used to repeat a set of instructions a determined
number of times. Sometimes it is the computer that knows how many times, not you, but it is still known.
To apply this concept of loops to an example we consider a situation in which we want to know what number
we obtain by adding the first 100 integer positive numbers, i.e. 1 + 2 + … + 100. For this example we use a
“for” loop.
As you can see when you run this example, if you place a semicolon (;) after a variable, the variable is not
written on the command window, on the other hand if you do not type a semicolon the value of the variable will
appear on the command window, as seen with the last instruction in our following program.
Program 2
clc % clears the command window
clear all %clears all variables from workspace
%for is the instruction used to start the loop
Sum = 0;
for i=1:100 %i is the variable that we use to run the numbers increasing
%from 1 to 100 in increments of 1
Sum = Sum + i; %Sum is the variable that stores the summation we are
%trying to determine
end
%end is the instruction used to close the loop
Sum
Let’s write another example of a program in which we use loops and in addition we use also vectors. The
program we will write now is aimed to produce the first 100 numbers of the Fibonacci sequence. As you know
the Fibonacci sequence is a series in which, excepting the first two elements, the following number is always
the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 … And in addition, the ratio
between two consecutive elements of the sequence approaches 1.61803…
For this program we will use two vectors, the first vector will store the first 100 elements of the Fibonacci
sequence while the second will store the ratio between two consecutive elements of the sequence.
Program 3
clc % clears the command window
clear all %clears all variables from workspace
FibSeq(1) = 0; %First number of sequence
FibSeq(2) = 1; %Second number of sequence
for i = 3:100 %in this case we start the loop at 3 because the first
%element we are going to determine is the third one, we
%already have the first 2 elements
FibSeq(i) = FibSeq(i-1) + FibSeq(i-2);
ratio(i-2)= (FibSeq(i)/FibSeq(i-1));%The variable ratio stores the
%ratio of the last two elements of the sequence
end
plot(ratio(1:20)); %Now we plot the first 20 elements of the variable
%ratio to demonstrate that it approaches 1.61803
grid on;
The variable FibSeq is a vector of 100 elements and stores every element of the Fibonacci sequence. You can
double–click on this variable on the Workspace window and it will show all 100 elements of the vector or you
can simply type “FibSeq” on the Command window and all 100 elements will be also listed. On the other hand,
the variable ratio stored the ratio between the last two elements of the sequence.
As a historical note, Leonardo Pisano Bigollo was the mathematician who created this sequence, his father was
Guglielmo Bonacci, and that is why Leonardo was known as Fibonacci (since the Italian word for “son” is
“figlio”, thus Fi(glio di)Bonacci, son of Bonacci) [1].
Continuing with our examples, let’s write now a program in which we use nested loops. A nested loop is a loop
within a loop, an inner loop within the body of an outer one. The way nested loops operate is by having the first
pass of the outer loop triggering the inner loop, which executes to completion. Then the second pass of the outer
loop triggers the inner loop again. This process repeats until the outer loop finishes. A break within either the
inner or outer loop will interrupt the process.
Then in our example we will use nested loops to give animation to the plot we created in the first program. To
produce this animation we will change the value of x that we evaluate in f(x) by one position [f (xi) = f (xi+1)] and
then assigning the first value of f (x) to the last f (x), i.e., f (xlast) = f (x1). Then we repeat this process a number
of times, therefore we will need an outer loop to have this sequence repeated several times.
Program 4
clc % clears the command window
clear all %clears all variables from workspace
% Since we want to have x varying from -3 to 5 we can use the following
% instruction that creates a vector with elements going from -3 to 5 in
% increments of 0.05
x = -3:.05:5.5;
% Now we define a variable that will play the role of f(x) let's say y
y = .3*x.^4 - 1.2*x.^3 - 2*x.^2 + 3*x;
%
%
%
%
As you can see, since x is a vector when we calculate say x to the power
4 we need to do it for each element of the vector x, this is done in
MATLAB language by putting a period between the variable and the
operation that needs to be performed.
[Rows Cols] = size(y); %The command “size” returns the number of rows and
%columns of a variable.
for j=1:600 %This outer loop will control the number of times the graph is
%plotted, in this case 600 times
y(Cols) = y(1);%Assign the value of f(x1) to f(xlast)
for i=1:Cols-1 %This inner loop is used to change the value of y by one position
%It runs from 1 to the number of elements in the vector
%minus 1 (Cols - 1)
y(i) = y(i+1);%Change the value of y by one position
end %close the inner loop
figure (1) %Figure (1) is the label we use for the plot we will create
plot(x,y); % plots in the horizontal axis vector x and in the vertical axis vector y
grid on %adds a grid to the plot
pause(.01) %This instruction delays the execution of the loop by .01 seconds,
%in this way we give the appearance of an animation to the
%plot that repeats 600 times
end %close the outer loop
MATLAB basic guide for ME3560
Part II–Three Dimensional Plots
Once we have learned how to create a 2–D graph, we proceed to learn how to generate a 3–D or a contour plot
using MATLAB. When creating a 2–D graph for y = f (x), it was necessary to first generate the values of x that
were going to be used to evaluate y. In a similar way, when creating a 3–D or a contour plot described by an
expression such as z = f (x, y) it is necessary to first create all the x and y values that are to be used to determine
z. Now, in the 2–D case since f (x) is function of only one variable (x), and both x and f (x) are vectors. For the
3–D case, since z is function of two variables then x, y, and z are described by matrices.
The instructions we will use to create 3–D and contour plots are “surf” and “contour”, respectively. The format
for these commands is similar: surf(X,Y,Z) or contour(X,Y,Z).
surf(X,Y,Z) creates a shaded surface using Z for the color data as well as surface height. X and Y are matrices
defining the x and y components of a surface. X and Y must be the same size as Z and must increase
monotonically.
contour(X,Y,Z) draws contour plots of Z. X and Y specify the x– and y–axis limits. X and Y are matrices
which must be the same size as Z, thus specifying a surface, as defined by the surf function. X and Y must
increase monotonically.
The coordinates (x, y) to be used in the determination of z = f (x, y) can be created using nested loops but much
easier approach is by using the command “meshgrid”:
[X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and y into arrays X and Y, which can be
used to evaluate functions of two variables and three-dimensional mesh/surface plots. The rows of the output
array X are copies of the vector x; columns of the output array Y are copies of the vector y.
These three new commands (surf, contour, and meshgrid) are the basic instructions we need to know for our
surface and contour plots, and we will apply them now in an example. Let’s say that we want to construct a 3D
plot [figure (1)], a contour plot [figure (2)], and a 3D and contour plots together in the same figure [figure (3)]
of a paraboloid described by the expression z = 3x2 + 1.5y2 where xϵ[-5;5] and y ϵ[-3;3]. We are going to use
increments of 0.05 in both variables.
Program 5
clc
clear all
x = -5:.05:5; %x is a vector
%to be used to
y = -3:.05:3; %y is a vector
%to be used to
containing the x-coordinates that are going
evauate z
containing the y-coordinates that are going
evaluate z
[X,Y] = meshgrid(x,y); %The instruction meshgrid creates, using vectors
%x and y two matrices X and Y containing the
%coordinates of the mesh over which we will evaluate
%z.
Z = 3*X.^2 + 1.5*Y.^2; %Matrix Z contains the value of z when evaluated at
%each one of the points defined by X and Y
figure (1)
surf(X,Y,Z) %Plots the values contained in matrices X, Y, and Z in a 3D figure
figure (2)
contour(X,Y,Z) %Creates a contour plot of Z on a system of coordinates
%defined by matrices X,Y.
figure (3)
surfc(X,Y,Z) %Plots the values contained in matrices X, Y, and Z in a 3D figure
% and plots on the same graph the contours, therefore this
% instruction combines surf and contour instructions
After you have run the previous program try writing after the commands surf and surfc the following two
instructions:
shading interp
rotate3d
And run the code again to see what you obtain.
This short tutorial will prepare us for the exercises we need to study in Chapter VI. At that point in the semester
we will go over one more tutorial directly related to our course to then solve some examples using Fluid
Mechanics theory along with MATLAB.
[1] Magno Alessandro Marzo, “L’Invenzione dei Soldi”, p. 169, 2013.
Download