You are on page 1of 19

NM/May17

AN INTRODUCTORY COURSE ON
MATLAB

(MDB 3053 NUMERICAL METHODS)


SEMESTER MAY 2017
MECHANICAL ENGINEERING DEPARTMENT

by Saeid Kakooei

Learning Outcomes:
By the end of the course, students should be able to
1. use MATLAB as a calculator tool
2. use MATLAB for matrix computation
3. use MATLAB as a plotting tool
4. use MATLAB as a programming tool to solve numerical problems

1
NM/May17

LESSON 1: GETTING STARTED WITH MATLAB

1.1 Introduction

MATLAB stands for MATrix LABoratory. MATLAB is a high performance software


package for technical computing. Its basic data element is matrix. One can use it to perform
numerical computations, and visualize the results without the need for time-consuming
programming. It also provides the facility to write programs and create commands for
special purposes as we do in the case of C, or FORTRAN languages.

MATLAB features a family of application-specific solutions called toolboxes which


are the built-in programmes consisting of collections of MATLAB functions (M-files) that can
solve particular classes of problems. The toolboxes available can be seen by clicking Launch
Pad (Fig. 1) from the View menu in MATLAB command Window.

Command
Window
Launch Pad

Command
History
Window

Fig. 1: Default desktop view showing Command Window (right), MAT LAB Launch Pad (top left), and
Command History Window ( bottom left)

1.2 Getting Started


There are several ways to open MATLAB (version 7).
a. Click the MATLAB icon in the desktop. If Matlab is successfully executed, a small pop
up window will appear with the Matlab logo. The command window will then appear,
displaying the prompt >>.

b. From the Start Menu Programs MATLAB > R2006a > MATLAB

1.3 Command window


When the MATLAB is started, a command window as shown in the figure appears on
the screen. >> is the command prompt similar to the DOS prompt. Commands can be typed
at this prompt followed by pressing Enter to execute and produce answer (ans = )

2
NM/May17

Command prompt >>

1.4 Calculations at the Command prompt

MATLAB can be used as calculator tool, simply by typing the command at the
command prompt. Consider the following operations.
>> -5/ (4.8+5.32)^2
ans = result assigned to ans
-0.048821 if name not given

>> (3+4i)*(3-4i)
ans =
25
argument is always in radian, pi =
>> cos(pi/2)
ans =
6.1232e-017

>> exp(acos(0.3))
ans = answer in radians
3.547

Priority of common arithmetic operators :


Priority Operation
1 (highest) Parentheses ( ) , innermost first
2 Exponentiation ^, left to right
3 Multiplication and division, left to right
4 (lowest) Addition and subtraction, left to right

1.5 Assignment of values to variable names

In order to store the answers and use their values at latter stages of calculations,
these values can be assigned to variables and use their names in calculations. For example,

>> a = 2 value assigned to variable a


and
>> A = 5 case-sensitive
>> a^A

Note how the assignment echoes to confirm what you have done. The screen output can be
suppressed by terminating the command line with semicolon (;) character. Try typing
>> b = -3; semicolon ; to suppress the screen output

>> msg = Hello UTP! Variable is assigned to a string character


3
NM/May17

Beware that MATLAB is case-sensitive. It means that a and A are two different variables.
The values stored by a variable can be examined by typing the name alone: A, or with more
detail, type in: who or whos
list workspace variables
>> whos

Name Size Bytes Class


A 1x1 8 double array

Useful keys to remember:


; to suppress the output results to the screen
arrow scroll through previously typed commands
Esc clear current typed command line
ctrl-C quit current operation and return control to the command line (useful for
breaking out of slow/stalled operation or excessive screen output)
>>clear remove all functions and variables from memory
>>clc clear the screen and display a fresh command window
>>help list help topics. For help in particular command, e.g. type >>help asin

1.6 Built-in Math Functions

MATLAB has many predefined built-in math functions. You can use online help to
find out more. These functions and the description can be retrieved when needed. Try:

>> help matlab\elfun

Try out the following:


Arc Sine of x: >>asin(X) use parentheses ( )
for argument input
Logarithm of x to base 10: >>log10(x)
Square root of x: >>sqrt(x)
Exponential of x: >>exp(x)
For more decimal
points
Output format : >> format long or format short

Useful Resources from Mathworks

Student center of Mathworks


http://www.mathworks.com/academia/student_center/

Step-by-step instructions on how to get started using MATLAB from Mathworks


http://www.mathworks.com/ matlabcentral/link_exchange/MATLAB/Academic_Curricula/Gener
al_Interest/MATLAB_Tutorials/index.html

4
NM/May17

LESSON 2: ARRAY & MATRICES IN MATLAB

2.1 Working with Arrays and matrices

MATLAB (MATrix LABoratory) has powerful features in handling matrices. MATLAB


treats all variables as arrays. An array is a collection of values that are represent by a single
variable name. One dimensional arrays are called vectors and 2-D arrays are called
matrices. Arrays can be created using statements as follows:

Row vector: element separated by either space or comma (,)


>> A = [1 2 3] or [1, 2, 3]
Column vector: elements separated by semicolon (;)
>> B = [4; 5; 6]
or by transposing a row vector with operator: >>B = [4 5 6]

Vector addressing: For example, to access the third element of A and second element of
B, we can type >> A(3) and >>B(2)

1 2
Matrix: To define this 2 x 2 matrix, >>C = 3 4

The following can be assigned: >>C = [1 2;3 4]

Matrix addressing: For example, to access the element in row-1 and column-2 of C, we
type >> C(1,2) ans = 2

default
2.2 Use of colon (:) increment is 1

Arrays can be assigned in the following simpler manner by use of colon (:)

For example, >>m = 1:10 denotes a row vector m=[1 2 3 4 5 6 7 8 9 10]


and >>n = 2:0.5:4 represents the row vector n=[2.0 2.5 3.0 3.5 4.0]
Start with 2, count up by 0.5 and stop at 4

2.3 Matrix Operations


The real power of MATLAB is illustrated in its ability to perform matrix calculation.
Matrix is a rectangular arrangement of number (called as element) in m rows and n columns.
It is called as (m x n) matrix. The common arithmetic operators are +,-,*,/,^. For more
operators, type >>help ops

For matrix multiplication (a*b), the inner product of two vectors can be calculated using the
* operator:
1x3 matrix
>>A = [1 2 3];
>>B = [3;2;1]; 3x1 matrix

>>A*B Inner dimension must be


ans = 10 equal: [1x3]*[3x1] = [1x1]
>>C = B*A
C =
3 6 9
2 4 6 [3x1]*[1x3] = [3x3] matrix
1 2 3 5
NM/May17

30 60 90
If you want to perform matrix multiplication, you can: C^2 = 20 40 60

>>C^2 equals to C*C 10 20 30

But if you want to square each individual element of C , this can be done with array operator:
>>C.^2
Note the dot . precedes the ^

For array multiplication (a.*b), the matrices must have the same dimensions and the
operation is performed at each element:
>>A = [1 2 3 4; 5 6 7 8]; [2x4]

>>B = [1:4; 1:4]; [2x4]


>>C = A.*B
Equal dimension:
C = 1 4 9 16 [2x4].*[2x4] = [2x4]
5 12 21 32
Same rules apply for other array operations e.g: .^ .* ./

2. 4 Left Division operator (\)


To solve a system of linear algebraic equation: Ax = b. We define the matrix A and the
vector b and use the following command:
>> A = [3 5 2; 2 3 -1; 1 -2 -3]; 3x1
3x1 + 5x2 + 2x3 = 8
>> b = [8; 1; -1]; 2x11 + 3x2 x3 =1
>> x = inv(A)*b x1 2x2 3x3 = 1
x =
ans ?

or simply enter:
>> x = A\b Use left division (\, the backslash) operator

x =

ans ??
2.5 Polynomial operations using Arrays

MATLAB has some convenient vector-based tools for working with polynomials. Type
help polyfun for more information.
The roots of polynomial can be found with the command roots( ). For example:
to find the roots of y = x3 4x2 + 5.25x 2.5 = 0, you type the coefficients and roots():
>>y = [1, 4, 5.25, 2.5]; equal to polynomial x 3 4x 2 + 5.25x 2.5
>>roots(y)

ans = 2.0000 1.0000+0.5000i 1.00000.5000i

To find the polynomial whose roots are 1 and 3 5i, you type command poly( ):
>>r = [1, 3+5i, 35i];
>>z = poly(r)
equal to polynomial x 3 7x 2 + 40x 34
Ans = 1 -7 40 34

To evaluate a polynomial, say y = x3 4x2 + 5.25x 2.5 at x = 1, we can type:


6
NM/May17
>>polyval(y,1)
Ans = -0.25 correspond to y(1) = (1)3 4(1)2 + 5.25(1) 2.5 = 0.25

7
NM/May17

LESSON 3: GRAPHICS IN MATLAB

3.1 Plotting

MATLABs graphics capabilities have similarities to those of a spreadsheet program.


Graphs can be created quickly and conveniently. There are functions defined in MATLAB to
carry out standard mathematical plots with simple command.
For example, to create a graph y versus t, enter:
>> t = [0 : 5 : 100];
Note the use of array operator: .^
>> y = t.^0.34 exp(-2.*t) +1./t; adjacent to numeric
>> plot(t,y)

This plot function is used to produce a 2D curve, using t- and y-data vectors.
We can customize or add additional info to the graph with commands like the following:
plot(t, y, clm)
>> plot(t,y, r:s);
>> title(Plot of y versus t);
>> xlabel (Values of \theta)
>> ylabel (Values of y)
>> grid on
place text in quotes
>> gtext(mid point) with mouse

To plot multiple lines:


>>plot (x1,y1,clm1,x2,y2,clm2,)

clm represent the color, line style and marker t ype by character as shown below
Colour Linetype Marker
Colour L Legend M Line type
C

y Yellow - Solid Circle


m Magenta : Dotted x x-mark
c Cyan -. Dashdot + Plus
r Red -- Dashed * Star
g Green s Square
b Blue d Diamond
Triangle
w White v
(down)
k Black < Triangle (left)
For example >> plot(t,y, r:s) to plot y(t) as red dotted line with square marker

3.2 Adding New curves


Try this: to plot the function y = sin(x) and y = e x
on a single graph
>>x=[0:0.1:2*pi]; ---- Note use of colon to create array
>>y=sin(x);
>>plot(x,y)
>>grid on
>>hold on ---- use hold command to add other lines on the same graph
>>z=exp(-x);
>>plot(x,z,r-*)
>>hold off
OR >> plot(x,y,b, x,z,r:)
8 -- to plot multiple curves
NM/May17

Title
Legend

gtext
Y label

Curve
y(x)

X label

3.3 Plotting Polynomials

Polyval( ) function is very useful for plotting polynomials. For example, to plot the
3 2
polynomial f(x) = 8x 5x + 3x + 7 for 2 x 5, you can type
>> a = [8, -5, 3, 7];
>> x = [-2:0.01:5]; xdata array
>> f = polyval(a,x);

>> plot(x,f, r-), xlabel (x), ylabel(f(x)), grid on

Other useful plot commands:


>> subplot
>> ezplot
>> plot3
>> ezsurf

For more information, type >>help graph2d

-0.2t
For example, to use ezplot to plot the function: y = e sin(2 t) , without specifying the
tdata range, we type: >> ezplot(exp(-0.2*t)*sin(2*t))

Or to specify t -data range,

we type: >> t=[-10:10]; ezplot(exp(-0.2*t)*sin(2*t),t)


9
NM/May17

LESSON 4: M-FILE PROGRAMMING

4.1 script M-File


MATLAB can be used in an interactive mode by typing each command from the
keyboard and perform the operation much like a calculator. However, this is sometimes
inefficient. For example, if the same set of commands is to be repeated a number of times
with different input values, then developing a MATLAB program will be quicker and efficient.
Script M-file is a MATLAB program consists of a sequence of language codes
written in a text file. Script M-file is created by using text editor and is necessary to give
a name to the M-file. The name should end with file extension of .m.

To create a new M-file, go to menu bar or click standard toolbar button for new file.

To create
new M-File

Try this: Type the following code in text editor and save the M-file iwith a filename called
my_convert.m. MATLAB will execute the script file as a single block of commands.
Script M-file is an m-file without the function declaration at the top of the code.
% script m-file my_convert.m
% comments the text that
% this program converts the temperature follows, that is, the line is
% from Fahrenheit to Celcius not executed by MA TLA B
%
%

x = input(Enter the temperature in deg F = )


y = 5/9*(x-32);
fprintf (The temperature is %4.1f deg C \n,y)

Note: semicolon ; will suppress the screen output

To run the M-file, go to command window and type the filename at the command prompt:
>> cd lesson:\ change directory
>> convert
enter a value here

Enter the temperature in deg F =

Note: To know more about script M-file, type >>help script


10
NM/May17

4.2 Function M-Files

Function M-file is another type of MATLAB program that can accept input
argument(s) and produce output(s) accordingly. At the top of the file must be a line that
contains the following syntax definition to declare the new function:

function [output_a, output_b] = func_name(input_x, input_y)

keyword to define output function input argument(s)


new function to argument(s) name
MATLA B library or multiple inputs

or multiple outputs

Try this: a script M-file can be easily coded into function M-file. Consider the script
my_convert_F.m and recode into a function M-file that accepts single input and single
output.

function [C] = my_convert_F(F)


% function m-file my_convert_F.m
% convert_F - convert Fahrenheit(F) to Celsius(C)
% F = input argument
% C = output argument
%
function body
C = 5/9*(F-32);
%
Note:

i. When you save, MATLAB will default the filename as my_convert_F.m.


ii. The function name must be unique and should not be similar to any built-in
functions in the MATLAB library. Try typing >>help my_convert_F
iii. To know more about function M-file, type >>help function

To run the function, go to command window and type the following at the command prompt:
change directory
>> cd lesson:\
>> F = 100;

>> C = my_convert_F(F) or C = my_convert_F(100)


C = 37.7778

4.3 MATLAB commands for INPUT/OUTPUT

input

If you want your M-file to prompt the user to supply an input, use the command input:

Try this: In the previous script M-file my_convert.m, we have the following line:

x = input(Enter the temperature in deg F = )

11
NM/May17
where the input command gives the user the prompt in the text string and then waits
for input from the keyboard. To know more, type >>help input

12
NM/May17

disp

The disp command can be used to display a message or the values of variable.
Try this: Go to command window or open a new M-file, type in:
>> b = [2 8 9 7]; c = Hello UTP!; ; suppress the display
disp(b)
disp(c)
disp(b.^2)
disp([The value b is ,num2str(a), only])
disp(2/7)

To know more, type >>help disp or >>help num2str


fprintf

In the last example, disp(2/7) displays the answer as 0.2857 (up to 4 decimals).
What can we do if we want the answer to be accurate to, say 6 decimal points? In such
case, use the command fprintf as follows:
fprintf(\n x=%10.6f \n, 2/7) %f for fixed-point real no.
fprintf(\n message c=%s \n, c)
%s to display string

fprintf displays the formatted data, x under the control of specified format string
like %10.6f in which:

%...f sign indicates what follows is a string printed as a fixed-point real number.
%...g sign indicates what follows is a string printed as a lowest format.
10.6 specifies that the field width is 10 and the number of decimal points is 6.
' \n ' sign means skip to next line. This allows the prompt string to span new line.

fprintf(\n x=%10.6f \n\n, 2/7) or try x=%0.6f \n\n

%f -decimal notation
%e exponential notation 10.6 specify the
/n to skip
field with = 10,
%s string character to new line
no of dec. pt = 6

To know more about other formatted output, type >>help fprintf

4.4 inline function

Function objects are created using the following syntax: inline(EXPR) in which the
MATLAB expression contained in the string EXPR. See >>help inline
Type >>f = inline(x^2 + y^2 + 2*x*y)
f = f(x,y) = x2 + y2 +2xy
Inline function:
f(x,y) = x^2 + y^2 + 2*x*y

Now the function can be evaluated by using any values for x and y. eg. type >>f(2,-4)
One way to plot the 3-D function f(x,y) is by using ezsurf
Type >>ezsurf(f);
For 2-D function like sin(2x), type
13
NM/May17
>>ezplot(sin(x))

14
NM/May17

LESSON 5: CONTROL FLOW COMMANDS IN MATLAB

MATLAB provide features that enable users to control the flow of command execution
depending upon certain decision structures. MATLAB offers four such control flow structures
that can be used in M-files. They are: if-else construct, for loops, while loops and
switch-case construct.
The execution of an if , for or while loops depends upon the evaluation of a
condition. To construct conditions, MATLAB provides six relational operators

Less than less than or equal == equal


greater than ~
greater than or equal = not equal

And three
and logical operators
three logical : & :and | or
operators ~ not

Note that the relational operator = = compares two arguments (a check for equality),
while = is used to assign a value to a variable.

15
NM/May17

5.1 if...else
if...else is a conditional statement for making decision in the execution of next
command. Statement will be executed only if the expression is true. It has the general form:
For multiple conditions:
if logical_expression
if logical_expression
<statement block #1> <statement block #1>
else elseif
<statement block #2> <statement block #2>
end else

<statement block #3>


end
Example: To evaluate multiple conditions:

n = input(Enter an integer, n =);


if n < 0
x = abs(n);
elseif (rem(n,2)==0)&(n~=0)
x = n/2;
else
x = n+1;
end
x

Example: Create algorithm of STEP 3 in Bisection method (refer lecture note of Chap 5)

test = func(xL)*func(xr);
if test < 0
xu = xr;
elseif test > 0
xL = xr;
else
ea = 0;
end

Try this: Create a script M-file to prompt user to enter ID no. If a negative ID is entered,
alert the user to re-enter, else display the ID.

5.2 for...end
for...end is a control flow statement for making repetition/iteration. It allows us to
execute a block of commands repeatedly for fixed number of times shown in figure (a). It has
the general form:
for index = start : increment : end
<statement block>
end the default increment is 1

Example: Create a M-file to sum up numbers from 1 till n: 1 + 2 + 3 + + n

16
NM/May17

sum = 0;
n = input(Enter an integer, n =)
for m = 1:1:n
sum = sum + m;
disp(m)
end
fprintf(\nThe total is = %g \n, sum)

Try this: Create a script M-file to compute the square values of numbers running from initial
value of 1 until it ends at 10. Each number is incremented by 1 each time.

5.3 while...end
while...end is another control flow statement. It allows repetition for an indeterminate
number of times as long as the test remains non-zero (true) as shown in Figure (b). It has
the general form:
initialization;
while test_expression
<statement blocks>
end

Example: find the smallest non-negative integer x such that 2x > a (given a = 106)

a = 1e6; a = 1e6;
x = 0; x = 0; (1)= while it is true
while 2^x <= a while(1)
x = x + 1; OR x = x + 1;

end if 2^x > a, break, end


fprintf(\nx = %g \n, x) end

fprintf(\nx = %g \n, x)

List of MATLAB Built-in Functions

intro < chol end function lu quit sprintf


help > clc eps global macro qz sqrt
demo = clear error grid magic rand startup
[ & clg eval hess max rcond String
] | clock exist hold memory real Subplot
( ~ conj exit home mesh relop Sum
) abs contour exp ident meta rem Svd
. all cos expm if min return Tan
, ans cumprod eye imag nan round Text
; any cumsum feval inf nargin save Title
% acos delete fft input norm schur Type
! asin det filter inv ones script What
: atan diag find isnan pack semilogx While
' atan2 diary finite keyboard pause semilogy Who
+ axis dir fix load pi setstr xlabel
- balance disp floor log plot shg ylabel
* break echo flops loglog polar sign zeros
\ casesen eig for logop prod sin
/ ceil else format ltifr prtsc size
17
NM/May17
^ chdir elseif fprintf ltitr qr sort

18
NM/May17

acosh demo hankel membrane print table1


angle demolist hds menu quad table2
asinh dft hilb meshdemo quaddemo tanh
atanh diff hist meshdom quadstep tek
bar eigmovie histogram mkpp rank tek4100
bench ergo hp2647 movies rat terminal
bessel etime humps nademo ratmovie toeplitz
bessela expm1 idft nelder readme trace
besselh expm2 ieee neldstep residue translate
besseln expm3 ifft nnls retro tril
blanks feval ifft2 null roots triu
cdf2rdf fft2 info num2str rot90 unmkpp
census fftshift inquire ode23 rratref vdpol
citoh fitdemo int2str ode45 rratrefmovie versa
cla fitfun invhilb odedemo rref vt100
compan flipx isempty orth rsf2csf vt240
computer flipy kron pinv sc2dc why

cond funm length plotdemo sg100 wow


conv gallery log10 poly sg200 xterm
conv2 gamma logm polyfit sinh zerodemo
corr getenv logspace polyline spline zeroin
cosh ginput matdemo polymark sqrtm
ctheorem gpp matlab polyval square
dc2sc graphon mean polyvalm std
deconv hadamard median ppval sun

List of useful MATLAB help files


>> help elmat Elementary matrices and matrix manipulation eg ones, zeros, linspace etc
>> help elfun Elementary math functions eg sin, asin, log, abs etc
>> help matfun Matrix functions numerical linear algebra eg det, \, lu, eig, poly etc
>> help general List of general purpose commands eg help, what, who, clear etc
>> help polyfun Polynomial and interpolation eg roots, polyval, interp2, spline etc
>> help ops List of operators and special characters eg +, *, : [], ./
>> help plotxy Two dimensional graphics eg plot, title, gtext, grid, fplot etc

REFERENCES
1. Introduction T o Matlab 7 for Engineers, William J Pa lm III, McGraw Hill
2. Applied Numerical Methods with Matlab f or Engineers and Sc ientiest, Steven C Chapra, McGraw H ill
3. Engineering and Scient ific Computat ions using Matlab, Sergey E Lyshevski, Wiley
4.

19

You might also like