Matlab Tutorial

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

MECH304 Applied Numerical Engineering

Tutorial on MATLAB fundamentals

The goal of this tutorial is to familiarize you with the fundamentals of Matlab (defining variables,
doing calculations and creating graphs). Later, we will use these fundamentals to develop Matlab
script files (programs) to solve more complicated models.

What can we use Matlab for?


1. Simple calculations
2. Plotting and analyzing mathematical relationships (2D and 3D)
3. Vector & Matrix Operations
4. Writing script files (a type of programming)
5. Symbolic manipulation of equations
6. Advanced visualization, animation and GUI interface tools

Matlab Basics

To start a MATLAB session (i.e. open a MATLAB window), click on the MATLAB Application
shortcut. After some time, a MATLAB window, similar to that shown in Figure 1, will appear.

Change current directory


by browsing for your
folder

Type your commands here

Figure 1 Matlab window


---------------------------------------------------------------------------

For calculations in this tutorial, we will be using the ideal gas equation

P*V = n*R*T

 P = Pressure in Atmospheres
 V = Volume (in Liters)
 n = Number of Moles of Gas
 R = 0.0821 Atm*Liters/mol*Kelvin
 T = Temperature in Kelvin

-----------------------------------------------------------------------------------------------------------------

1. Creating and using variables


o Type in Command Window P=1<ENTER> n=1<ENTER> R=0.0821<ENTER>
T=273<ENTER>

o Variable names are case sensitive (so T is not the same is t). Variable names can
include letters or numbers
o Other legal variable names would be Pressure, Vol, nMoles, Rvalue, T1, ...
2. You can recall previous lines by using up-arrow key
3. Arithmetic Operations & Simple Calculations (+, -, *, /, ^)
o The volume can be determined by typing V= n*R*T/P
4. The role of the Semi-colon in Matlab
oMatlab will print out the answer for any command not terminated by a semi-colon.
oMatlab will not print out the result if the line ends in a semi-colon
5. To find out help on a command (such as plot), type help plot (or use the pull down help
menu)

Arrays & Arrays Arithmetic

In addition to doing operations on single numbers, Matlab allows us to perform operations on a list
of numbers. These lists are also called Vectors, Arrays or Matrices in the Matlab manuals.

1. There are several ways to create a vector


o Using the Colon notation, e.g. T= 300:10:400

In general using [ a : b : c ] where a , b and c are numbers will create a row vector whose 1st
element is a , second element a + b etc and whose last element is no greater than c (if b > 0 , no less
than c if b < 0). If there are only two numbers then MATLAB assumes the increment (b above) is 1.
o Using the zeros and ones commands, e.g. y=zeros(1,3); z = ones(1,5);
o Explicitly listing terms, e.g. x = [1 4 9 16]
o Reminder: If you do not include a semi-colon, the entire list will be printed
2. We can do addition, subtraction, multiplication and division of a list and a value using the
(+, -, *, /) operators. Try, for example, T*2 , T/5, T+20, T/10+5
3. Array operations on a list when you include dot operator “.”(.* ./ and .^ operators)
operate on each element of the list individually
4. Try x=1:3, y=2:4 then type operations like x.*y, x./y, x.^y
5. Type in T=300; V = 10:20; P=n*R*T./V to get the pressure at several different volumes
6. There are many intrinsic Functions (sin, cos, exp, ...) which can operate on list elements.
angle=0:pi/4:pi, sin(angle)

Creating Plots

1. To plot two arrays (vectors), enter a command such as plot(V,P)


2. To select axis range use the axis command with a 4 element list containing [xmin, xmax,
ymin, ymax], e.g. axis([5 8 1 2])
3. To set colors and line types use optional plot arguments
o plot(V,P,'ro') or plot(V,P,'b--')
4. To overlay graphs, type hold on and subsequent graphs will be on the same axes. To start a
new graph, type hold off
5. Labels and titles can be added by using commands such as
o xlabel('Volume (in Liters)')
o ylabel('Pressure (in Atm)')
o title('Ideal Gas Plot')

6. To zoom in on a graph, type zoom on and highlight a region with a mouse

Matlab Script Files (or M-Files)

We can simplify repetitive tasks by storing a series of Matlab commands in a script file (later we
will use these to write powerful programs)

1. Use "New, M-File" under file menu or use any text editor
2. Type in a series of commands, such as
o n=1;
o R=0.0821;
o T=300;
o V=10:.5:30;
o P300 = n*R*T ./ V;
o T=200;
o P200 = n*R*T ./ V;
o plot(V,P200,'r-',V,P300,'g:')
o legend('T=200 Kelvin','T=300 Kelvin')
o xlabel('Volume (Liters)')
o ylabel('Pressure (Atmosphere)')

3. Save as file name plotgas.m


4. In the Matlab command window, type in plotgas and it will run your series of commands
5. You can ask the user to enter input by using the input command. Change the definition of n
to read
o n = input('Enter Number of Moles of Gas ');
6. Any text following a percent sign (%) is treated as a comment by Matlab

Matrices

To fully understand how Matlab uses matrices, we must discuss a bit about linear algebra.
1. When we define a list using a command such as t=1:3, Matlab creates a row vector
containing 3 elements.
2. A row vectors can be turned into a column vector using the transpose (') operator. Using the
definition of t above, note what happens for the command t' and t''
3. The multiplication, division and exponential operators (*, /, ^) operating on two vectors
will do matrix multiplications, not multiplying the elements together.
4. Given a list x=0:2:10; then x.*x or x.^2 will give a list with the squares of the even
integers [0 4 16 36 64 100] because it is doing list or array multiplication
5. The command x*x will produce an error (since you can't do matrix multiplication of two
row vectors together).
6. The command x*x' be will give the value of 220 (0+4+16+36+64+100=220) since the
transpose operator (') means that we have a row times column matrix (resulting in a scalar).
7. The command x'*x will result in a 6 by 6 matrix
8. We can extract and modify elements of a list
o Selecting an element of a list, use x(3)
o We can set an element using x(3)=100;
o To select a range of a list, use x(3:5) or x(:3) or x(5:)

Two Dimensional Matrices and Three Dimensional Functions

1. A 3x3 matrix can be initialized using . y = zeros(3)


2. Using explicit references, e.g. A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
o Elements in each row are separated by spaces or commas
o Each row is separated by a semicolon or by pressing the return key
3. Array operations (+ - .* ./ .^) operate on each element of a matrix, For example, try
A.^2 or A.*A

4. Matrix operations are (+ - * / ^), For example, try A^2 or A*A


5. We can extend two 1-D vectors to a 2-D matrix (which we can use for calculations) use
meshgrid

6. For example, we can make a multiplication table using array multiplication


o x = 1:5
o y = 0:3
o [X Y] = meshgrid(x,y)
o B = X .* Y
7. Plot using mesh, surf, contour
8. Calculate and Plot sinc(R)=sin(R)/R using (MAKE SURE YOU USE .^ and ./)
o x = -16:1.1:16;
o [X Y] = meshgrid(x,x);
o R = sqrt(X.^2 + Y.^2);
o SincR = sin(R)./R;
o surf(X,Y,SincR)
o colorbar

9. You can select subranges of matrices, A(3,3) or A(1:2,1:2) or A(1:2,:) or A(:,2:3)

You might also like