A picture is worth a thousand words, particularly visual representation of data in engineering is very useful. MATLAB has powerful graphics tools and there is a very helpful section devoted to graphics in MATLAB Help: Graphics. Students are encouraged to study that section; what follows is a brief summary of the main plotting features.
plotStatement
Probably the most common method for creating a plot is by issuing plot(x, y)
statement where function y is plotted against x.
Type in the following statement at the MATLAB prompt:
x=[-pi:.1:pi]; y=sin(x); plot(x,y);
After we executed the statement above, a plot named Figure1 is generated:
Having variables assigned in the Workspace, x and y=sin(x) in our case, we can also select x and y, and right click on the selected variables. This opens a menu from which we choose plot(x,y). See the figure below.
Graphs without labels are incomplete and labeling elements such as plot title, labels for x and y axes, and legend should be included. Using up arrow, recall the statement above and add the annotation commands as shown below.
x=[-pi:.1:pi];y=sin(x);plot(x,y);title('Graph of y=sin(x)');xlabel('x');ylabel('sin(x)');grid on
Run the file and compare your result with the first one.
help gtext help legend help zlabel
If you want to merge data from two graphs, rather than create a new graph from scratch, you can superimpose the two using a simple trick:
% This script generates sin(x) and cos(x) plot on the same graph % initialize variables x=[-pi:.1:pi]; %create a row vector from -pi to +pi with .1 increments y0=sin(x); %calculate sine value for each x y1=cos(x); %calculate cosine value for each x % Plot sin(x) and cos(x) on the same graph plot(x,y0,x,y1); title('Graph of sin(x) and cos(x)'); %Title of graph xlabel('x'); %Label of x axis ylabel('sin(x), cos(x)'); %Label of y axis legend('sin(x)','cos(x)'); %Insert legend in the same order as y0 and y1 calculated grid on %Graph grid is turned
Multiple plots in a single figure can be generated with subplot
in the Command Window. However, this time we will use the built-in Plot Tools. Before we initialize that tool set, let us create the necessary variables using the following script:
% This script generates sin(x) and cos(x) variables clc %Clears command window clear all %Clears the variable space close all %Closes all figures X1=[-2*pi:.1:2*pi]; %Creates a row vector from -2*pi to 2*pi with .1 increments Y1=sin(X1); %Calculates sine value for each x Y2=cos(X1); %Calculates cosine value for each x Y3=Y1+Y2; %Calculates sin(x)+cos(x) Y4=Y1-Y2; %Calculates sin(x)-cos(x)
Note that the above script clears the command window and variable workspace. It also closes any open Figures. After running the script, we will have X1, Y1, Y2, Y3 and Y4 loaded in the workspace. Next, select File > New > Figure, a new Figure window will open. Click "Show Plot Tools and Dock Figure" on the tool bar.
Under New Subplots > 2D Axes, select four vertical boxes that will create four subplots in one figure. Also notice, the five variables we created earlier are listed under Variables.
After the subplots have been created, select the first supblot and click on "Add Data". In the dialog box, set X Data Source to X1 and Y Data Source to Y1. Repeat this step for the remaining subplots paying attention to Y Data Source (Y2, Y3 and Y4 need to be selected in the subsequent steps while X1 is always the X Data Source).
Next, select the first item in "Plot Browser" and activate the "Property Editor". Fill out the fields as shown in the figure below. Repeat this step for all subplots.
Save the figure as sinxcosx.fig
in the current directory.
3D plots can be generated from the Command Window as well as by GUI alternatives. This time, we will go back to the Command Window.
plot3Statement
With the X1,Y1,Y2 and Y2 variables still in the workspace, type in plot3(X1,Y1,Y2)
at the MATLAB prompt. A figure will be generated, click "Show Plot Tools and Dock Figure".
plot3
.
Use the property editor to make the following changes.
The final result should look like this:
Use help
or doc
commands to learn more about 3D plots, for example, image(x)
, surf(x)
and mesh(x)
.
To plot vectors, it is useful to draw arrows so that the direction of the arrow points the direction of the vector and the length of the arrow is vector’s magnitude. However the standard plot function is not suitable for this purpose. Fortunately, MATLAB has quiver
function appropriately named to plot arrows.
quiver(x,y,u,v)
plots vectors as arrows at the coordinates (x,y) with components (u,v). The matrices x, y, u, and v must all be the same size and contain corresponding position and velocity components.
Calculate the magnitude of forces OA, OB and the resultant R of OA and OB shown below. Plot all three forces on x-y Cartesian coordinate system1.
% Preparation clear % removes all variables from the current workspace, % releasing them from system memory. clc % clears all input and output from the Command Window display, % giving you a "clean screen." % Input and Computation OA=[600 320]; % Force 1 magOA=sqrt(sum(OA.^2)); OB=[-200 -480]; % Force 2 magOB=sqrt(sum(OB.^2)); OC=OA+OB; % The resultant of OA and OB magOC=sqrt(sum(OC.^2)); % The magnitude of resultant force OC angleMag=atan(OC(2)/OC(1))*180/pi; % angle of OC in degrees % Output disp(' ') % Display blank line str1= ['The magnitude of the resultant force is ', num2str(magOC), ' N.']; disp(str1); str2= ['The angle of the resultant force is ', num2str(angleMag), ' degrees.']; disp(str2); % Plot Preparation starts = zeros(3,2); % Origin for all 3 forces, 3x2 "zero" matrix ends = [OA;OB;OC]; % End point for all 3 forces vectors = horzcat(starts,ends); % Concatenate arrays horizontally % Plot Forces on x-y Cartesian Coordinate System % The following MATLAB function plots vectors as arrows % at the coordinates specified in each corresponding % pair of elements in x and y. quiver( vectors( :,1 ), vectors( :,2 ), vectors( :,3 ), vectors( :,4 )); axis equal grid title('Forces on x-y Cartesian Coordinate System') xlabel('x') % x-axis label ylabel('y') % y-axis label view(2) % setting view to 2-D
quiver
function.
Write an interactive script to calculate the resultant R of forces F1, F2 and F3 shown below and plot all four forces on x-y Cartesian coordinate system2.
clear clc disp('This script computes the resultant of three forces on x-y Cartesian coordinate system.') f1=input('Enter the magnitude of first force in N: '); theta1=input('Enter the angle of first force in deg: '); f2=input('Enter the magnitude of second force in N: '); theta2=input('Enter the angle of second force in deg: '); f3=input('Enter the magnitude of third force in N: '); theta3=input('Enter the angle of third force in deg: '); x1=f1*cos(theta1*pi/180); % The components of force y1=f1*sin(theta1*pi/180); % The components of force F1=[x1 y1]; % Force 1 x2=f2*cos(theta2*pi/180); % The components of force y2=f2*sin(theta2*pi/180); % The components of force F2=[x2 y2]; % Force 2 x3=f3*cos(theta3*pi/180); % The components of force y3=f3*sin(theta3*pi/180); % The components of force F3=[x3 y3]; % Force 3 R=F1+F2+F3; % The resultant of F1, F2 and F3 magR=sqrt(sum(R.^2)); % The magnitude of resultant force R angle=atan(R(2)/R(1))*180/pi; % Angle of R in degrees disp(' ') % Display blank line str1= ['The magnitude of the resultant force is ', num2str(magR), ' N.']; disp(str1); str2= ['The angle of the resultant force is ', num2str(angle), ' degrees.']; disp(str2); starts = zeros(4,3); ends = [F1;F2;F3;R]; ends(3,3)=0; % inputs 0s for z components, making it 3D vectors = horzcat(starts,ends); % Concatenate arrays horizontally quiver3( vectors( :,1 ), vectors( :,2 ), vectors( :,3 ), vectors( :,4 ), vectors( :,5 ), vectors( :,6 )); % A three-dimensional quiver plot displays vectors with components (u,v,w) at the points (x,y,z), where u, v, w, x, y, and z all have real (non-complex) values. axis equal title('Forces on x-y Cartesian coordinate system') xlabel('x') % x-axis label ylabel('y') % y-axis label view(2)
quiver3
function.
plot(x, y)
and plot3(X1,Y1,Y2)
statements create 2- and 3-D graphs respectively,title
, xlabel
, ylabel
and legend
,quiver
and quiver3
plots are useful for making vector diagrams.