Department of Metallurgical Engineering and Materials Science, IIT Bombay
Department of Metallurgical Engineering and Materials Science, IIT Bombay
In this tutorial, we will learn how to use MATLAB for simple mathematical operations and
plotting. In this tutorial, all commands/functions for MATLAB are written using the Courier
font.
L0.1: At the terminal, type matlab to open the MATLAB environment. A typical MATLAB
environment has multiple panels: Command Window, Command History, Workspace, and
Current Folder. Panels may be added or removed by selecting from the Layout tab. All
MATLAB commands are to be written at the command prompt (>>) in the Command Window.
Command History shows all the previously used commands. Workspace shows all the variables
and data used in the current session. Current Folder shows all the files in the folder.
L0.2: MATLAB is well documented. Help for all commands can be obtained by:
L0.3: Basic calculator functions can be performed at the command prompt in MATLAB. For
example,
>> sin(pi/4)*exp(pi)
MM612: Tutorial 1 1
gives the output
ans =
16.3629
Here, sin() is the function for calculating the sine of a number, exp() is the function for
calculating the exponential of a number, and pi is π . Functions for most of the common
mathematical operations exist in MATLAB and can be found from the documentation.
L0.4: Before beginning a new session/writing new code in MATLAB, it is always good
practice to clear existing data (unless of course we want to work with existing data). This can be
done using:
>> clc;
Note: It is always a good practice to end MATLAB commands with a semicolon (;), especially
when writing long pieces of code. This suppresses the output of the current command.
Unlike programming languages such as C, C++ and Fortran, variables need not be defined a
priori in MATLAB, although it is always a good practice to do so, especially for
multi-dimensional matrices.
L1.1: Use:
>> a = 5;
to create a 1x1 matrix called a with a value of 5 assigned to it. The value of a can be queried
using:
>> a
a =
5
MM612: Tutorial 1 2
L1.2: Now, we create a vector b of dimension 5 with values (10 20 30 40 50) using:
Note that when defining vectors or matrices, we use the square brackets [] in MATLAB. The
columns of the vector are separated by blank spaces or tabs ( ).
>> b(2)
ans =
20
Note that we use round brackets () when querying the value of an element in a vector. The
index 2 refers to the 2nd element of the vector. In MATLAB, the matrix index starts from 1.
This is unlike C/C++, where the matrix index starts from 0.
L1.4: If we want to modify or assign another value to an element of the vector, this can be
simply done using:
MM612: Tutorial 1 3
c is a matrix with 5 rows and 4 columns. Columns are separated by blank spaces or tabs ( ),
while rows are separated by semi-colons (;).
>> c(5,1)
ans =
17
L1.6: We can use the function size to query the dimensions of any vector or matrix:
>> size(a)
ans =
1 1
>> size(b)
ans =
1 5
>> size(c)
ans =
5 4
Note that all variables are defined as matrices in MATLAB. For example, the variable a has
dimension 1x1.
For example, we can define a vector b2 with the value of the first element as 10 and the last
element as 50, and having elements with equal spaced intervals of 10:
>> b2 = 10:10:50;
>> b2
b2 =
10 20 30 40 50
Note that the elements of vector b2 have the same values as vector b initialized in L1.2.
To initialize a 1x5 matrix with all elements having the value 0, we use:
>> b3 = zeros(1,5);
MM612: Tutorial 1 4
To initialize a 5x4 matrix with all elements having the value 0, we use:
>> c2 = zeros(5,4);
To initialize a 5x4 matrix with all elements having the value 1, we use:
>> c3 = ones(5,4);
Note that if only one dimension is provided, a square matrix is initialized, i.e.,
>> d = zeros(3);
>> d
d =
0 0 0
0 0 0
0 0 0
>> b3 = linspace(10,50,5);
Here, b3 has 10 as the first element and 50 as last element, and a total of equally spaced 5
elements.
MATLAB provides a variety of functions for matrix operations. This is the main benefit of using
MATLAB over other programming languages such as C, C++ or Fortran.
For the lessons in this Section, let us first define a 3x3 square matrix d2 as:
>> d2 = [1 2 3; 4 1 6; 7 8 1];
MM612: Tutorial 1 5
L2.2: The inverse of d2 can be obtained by:
>> d4 = inv(d2);
>> d5 = d2 * d3;
L2.4: Instead of matrix multiplication, if we simply want to multiply an element of one matrix
with the corresponding element of another matrix, we use:
>> d6 = d2 .* d3;
Note that the . operator can lead to unwanted results if not used carefully. IT IS NOT TO BE
CONFUSED WITH MATRIX MULTIPLICATION.
>> d7 = 5 * d6;
This is only a small list of useful functions and operations. Refer to the documentation for more
advanced functions in MATLAB!
L2.8: Now we will learn how to use conditional statements in MATLAB. Let us use the b
vector defined in L1.2. We will try to find the number of elements in the vector that have a
value greater than or equal to 30.
>> counter = 0;
>> b = [10 20 30 40 50];
>> for i = 1:length(b)
MM612: Tutorial 1 6
if (b(i) >= 30)
counter = counter + 1;
end
end
Here, the variable counter counts the number of elements having a value greater than or equal
to 30. We use the for loop to iterate over all the elements of the vector. Note the function
length, which can be used to find the number of elements in a vector. We loop over the
elements using i and the conditional if statement checks if the value of b(i) is greater than or
equal to 30. Both the for loop and the if block need to have an end statement to indicate the
end of the respective blocks.
MATLAB can be used for different types of plotting, both 2D and 3D. Here we will go through a
few of them.
L3.1: We will first start with creating a 2D line plot of a trigonometric function.
>> x = [-pi:pi/20:pi];
>> y1 = sin(x);
>> plot(x,y1,’Color’,’r’);
>> xlabel(‘x’);
>> ylabel(‘sin(x)’);
>> xlim([-pi pi]);
>> ylim auto;
Here, plot(x,y1,’Color’,’r’) is used for plotting a 2D line plot of x vs. sin(x) with
a red (‘r’) line. xlabel and ylabel are used for specifying the axis labels, while xlim and
ylim are used for specifying the axis limits.
hold on; retains the current plot and axis properties. plot(x,y2,’Color’,’g’); plots
x vs. y2 in green (‘g’) color.
MM612: Tutorial 1 7
Finally, >> legend(‘sin(x)’,’cos(x)’); adds the legend for the two lines to the plot.
>> print(‘plot1’,’-depsc’); saves the plot to plot1.eps file. ‘-depsc’ specifies the
format (.eps). This may be replaced with ‘-dpng’ to save to a .png file. We just created our
first plot in MATLAB!
The equation of a helix is given as: x(t) = cos(t); y(t) = sin(t); z(t) = t . We can implement this
in MATLAB as:
L3.3: Now we will learn how to create a surface plot in MATLAB. For this example, we will
plot the equation: z = x2 + y 2 .
MM612: Tutorial 1 8
Here, we use a new function meshgrid to create a 2D grid with the two axes, x and y,
represented by the two vectors x1 and y1, respectively. Note the use of the . operator. We then
plot z using the surf function to create a surface plot. If we want a mesh plot instead of a
surface plot, we can use mesh(x,y,z).
All MATLAB commands written at the terminal can also be written in the form of a script and
executed. This allows reusability of the code for future applications. As an example, we put
together the code written in L3.3 in a function and then execute it. We create a file called
example_plot.m:
function example_plot(deltax,xmax,deltay,ymax)
% First MATLAB function
% Define grid
x1 = [0:deltax:xmax];
y1 = [0:deltay:ymax];
[x,y] = meshgrid(x1,y1);
% Define function
z = x.^2 + y.^2;
% Plot z
surf(x,y,z);
% Label axes
xlabel(‘x’);
ylabel(‘y’);
zlabel(‘x^2 + y^2’);
The name of the function is example_plot and we pass the grid parameters deltax, xmax,
deltay and ymax to the function. Also note that any line or statement that starts with a % is
considered as a comment in MATLAB. It is not executed during run time.
>> example_plot(0.1,1,0.1,2)
We just created our first function in MATLAB. Now we can play around with the grid
parameters and see how this alters the surface plot!
MM612: Tutorial 1 9
Assignments
Create a folder called MM612_Rollno on your desktop. All your scripts and plots should be
saved in this folder. At the end of the lab, only the files inside this folder will be used for
grading. Put the following header text (commented) at the beginning of all your scripts/functions:
% Name:
% Roll no.:
Assignment 1:
Create a MATLAB function called MM612A1 with the file name MM612A1.m.
Assignment 2:
Create a MATLAB function called MM612A2 with the filename MM612A2.m.
The harmonic motion of a block attached to a spring is given by the differential equation:
2
m ddt2x + b dx
dt
+ kx = 0
where, m is mass of the block, b is the damping coefficient, and k is the force constant of the
spring. The solution to this differential equation is of the form:
x(t) = Ae−bt/2m cos(ω′t + ϕ)
where, A is the amplitude and ω′ = √(k/m – b2 /4m2 ) is the angular frequency of the damped
simple harmonic motion. For m = 1 kg, k = 1 kg/s2 , A = 1 m , consider two cases: (1)
b = 0.1 kg/s , and (2) b = 0 (undamped motion).
(a) On the same graph, plot the position of the block for the two cases. Use red color for
case (1) and green color for case (2). Save your plot in the file MM612A21.png.
(b) Now plot the potential energy, kinetic energy, and total energy for case (1) on the same
graph (MM612A22.png), and for case (2) on a different graph (MM612A23.png).
Plot all data for a total time of 30 s. Label your axes and plots properly. Assume ϕ = 0 .
Does the total energy of the system decay for the damped case?
MM612: Tutorial 1 10