byMohamed Hussein
INTRODUCTION TO MATLAB
compliments to
Prof. Michael NegnevitskyUniverity of Tasmania
Lecture 1
Introduction to Matlab
Basic FeaturesScientific FeaturesArray OperationsScript Files or M-files
Basic FeaturesMatlab is a tool for doing numerical computations with matrices and vectors. It can also display information graphically. I will give an introduction to some of the most useful features of Matlab. I will include plenty of examples.The best way to learn to use Matlab is to run Matlab, trying the examples and experimenting.
MATLAB IDE
Simple MathMatlab can be used as a calculator (Text in yellow is what you type, text in white is what the computer “types” back):
>> 2 + 4ans =
6 >> ans * 3ans =
18
>> 4*5 + 2*4 - 8/2ans =
24
Operation Symbol Example
Addition, a + b Subtraction, a – b Multiplication, a × b Division, a ÷ b Power, ab
+
–
* /
^
2 + 3 5 – 4 3.14 * 0.21 8 / 2 5 ^ 2
Expressions are evaluated from left to right.
Order of precedence
1st - parentheses, ( ) ~ begins with the innermost2nd - exponentiation, ^3rd - multiplication, X and division, /4th - addition, + and subtraction, -
TEST YOUR UNDERSTANDING
Use MATLAB to compute the following expressions:
( ) 337.01/4
2
10512257 b.
)5(84)5(3
815112 a.
−×++
++
+⎟⎠⎞
⎜⎝⎛
can use (5e-3)
answer: a. 321.6925 b. 18.1653
The Matlab WorkspaceMatlab remembers the commands you enter as well as the values of any variables you create. These command and variables are said to reside in the Matlab Workspace and can be recalled whenever you wish.
>> a = 4a =
4 >> aa =
4
Number Display Formats
When a result is an integer, Matlab displays it as an integer.
>> a = 4;>> b = 2;>> c = a*bc =
8
Number Display Formats
When a result is a real number, Matlab displays it with four digits to the right of the decimal point.
>> a = 4;>> b = 3;>> c = a/bc =
1.333
Variables in Matlab
Variables are case sensitive (fruit, Fruit and FRUIT).Variables can contain up to 63 characters (in MATLAB 7).Variables must start with a letter, followed by any number of letters, digits, or underscores.
Special Variables & Constants
The following names should be avoided to be used as variables
ans - temporary variable containing the computed answer
eps - specifies the floating point precision accuracyi,j - imaginary unit; √-1Inf - infinity; ex. 5/0NaN - not a number/undefined result; ex. 0/0pi - mathematical constant π or 3.1415926 … 6959
When Matlab performs a calculation, it does so using the values it knows at the time the requested command is evaluated.
>> a = 4;>> b = 3;>> c = a + bc =
7>> b = 5;>> cc =
7
Variables in the Matlab workspace can be unconditionally deleted by using the command clear.
>> clear a>> a??? undefined function or variable ‘a’. >> clear>> b??? undefined function or variable ‘b’.
Other command and symbols for managing work session are:
clc - clears the Command windowexist (‘name’) - check the existence of file or variable ‘name’quit - quits MATLABwho - displays variables currently usedwhos - displays current variables and sizes: (colon) - generates an array with regularly spaced elements, (comma) - separates array elements; (semicolon) - suppresses screen display/a new row in an array… (ellipsis) - (three dots) continues in the next line% (percent) - begins of remarks/comments
Numeric Display Formatformat xxx is used to controls how numbers are displayed . Format commands available in MATLAB are:
format short - (default) four decimal digits; ex. ans = 789.1234format long - 16 digits; ex. ans = 0.123456789123456format short e - four decimal (maximum five digit ) with exponent;
ex. ans = 7.8912e+02 (denotes 7.8912 x 104)format long e - 16 digits (with 15 decimals) with exponent;
ex. ans = 1.234567891234500e-01(denotes 1.234567891234560 x10-1)
format bank - two decimal digits; ex. ans = 789.12format + - displays either +ve, -ve or zero; ex. ans = +format rat - approximation in ratio; ex. ans = 133/100 (from a
calculated value of 1.33)
Numeric Display Format (cont.)
format compact - suppresses excess line feeds to show more output in a single screen
format loose - revert to less compact display
To see which type is currently in use, type
get(0,'Format')
To see if compact or loose formatting is currently selected, type
get(0,'FormatSpacing')
SummaryMatlab knows addition (+), subtraction (–), multiplication (*), division (/), and power (^).Matlab evaluates expressions from left to right giving precedence to powers over multiplication and division and these over addition and subtraction.As a default, Matlab stores results in the variable ans.Matlab 7 remembers only the first 63 characters of a variable name.Variables must begin with a letter.Matlab is case sensitive.
Scientific FeaturesMatlab offers many common functions important to mathematics, engineering, and the sciences. Matlab handles complex numbers.
>> a=sqrt(9)/2a =
1.5000 >> b=sin(a/2)b =
0.6816>> c=round(a)*(b*180/pi)c =
78.1100
Common Mathematical Functions
Complex Numbers
Consider the quadratic equation:a x2 + b x + c = 0The roots of this equation are given by
aacbbxx
24,
2
21−±−
=
Let’s find solution using Matlab ifa = 1, b = 5, and c = 6
>> a = 1; b = 5; c = 6;>> x1 = (- b + sqrt(b^2 - 4*a*c))/(2*a)x1 =
-2 >> x2 = (- b - sqrt(b^2 - 4*a*c))/(2*a)x2 =
-3In this case, the term inside the square root is positive and the two roots are real numbers.
Let’s find solution if a = 1, b = 4, and c = 13.
12131444,
2
21 ×××−±−
=xx
;1321 −+−=x
;1322 −−−=x
The solution is complex. The terms -2 in x1and x2 are the real part of the solution. The terms 3 and -3 are the imaginary parts of the solution.
>> a = 1; b = 4; c = 13;>> x1 = (- b + sqrt(b^2 - 4*a*c))/(2*a)x1 =
-2.0000 + 3.0000i>> x2 = (- b - sqrt(b^2 - 4*a*c))/(2*a)x2 =
-2.0000 - 3.0000iA complex number is written as a + bi in which a is the real part, b is the imaginarypart, and i = √-1.
In Matlab, the conversion between polar and rectangular forms make use of the functions real, imag, abs, and angle:
>> a = 1-2ia =
1.0000 - 2.0000i>> abs(a)ans =
2.2361>> real(a)ans =
1
>> imag(a)ans =
-2>> b_angle = angle(a)b_angle =
-1.1071>> b_deg = b_angle*180/pib_deg =
-63.4349
Other Mathematical Functions
exp (x) - ex
log (x) - ln xlog 10(x) - log10 xcos (x) - cosine xsin (x) - sine xtan (x) - tangent xacos (x) - arc-cosine xasin (x) - arc-sine xatan (x) - arc-tangent x
SummaryMatlab has many mathematical functions.Complex numbers require no special treatment in Matlab.The default value of i (and j) is √-1. Appending i (or j) to the end of a number tells Matlab to make the number the imaginary part of a complex number
>> a = 2ia =
0 + 2.0000i
Array OperationsTo create an array in Matlab, you need to start with a left bracket, enter the desired values separated by space, then close the array with a right bracket.>> a = [2 4 6]a =
2 4 6 >> b = [(1 -2i) 4 (6 -3i)]b =
1.000 - 2.000i 4.0000 6.0000 - 3.000i
Array Addressing
In Matlab, individual array elements are accessed using subscripts:>> a(2) % The second element of aans =
4>> b(3) % The third element of bans =
6.0000 - 3.000i
Array Addressing (cont.)To access a block of elements at one time, Matlab provides colon notation
>> a = [1 2 3 4 5 6]a =
1 2 3 4 5 6 >> a(1:3)ans =
1 2 3
This is the first through third elements in a. 1:3says: “starts with 1 and count up to 3”.
Array Addressing (cont.)>> a = [1 2 3 4 5 6]a =
1 2 3 4 5 6 >> a(3:-1:1)ans =
3 2 1
This is the third, second and first elements in reverse order. 3:–1:1 says “starts with 3, count down by 1, and stop at 1”.
Array Addressing (cont.)>> a = [1 2 3 4 5 6]a =
1 2 3 4 5 6 >> a(2:2:6)ans =
2 4 6
This is the second, fourth and sixth elements in a. 2:2:6 says “starts with 2, count up by 2, and stop when you get to 6”.
Array Construction
>> a = [1 2 3 4 5 6];>> b = [5 6 7 8];>> c = [a b]c =
1 2 3 4 5 6 7 8 >> d = [a(1:3) 9 10]ans =
1 2 3 9 10
More on ArrayTo create a regularly spaced array>> a = [0:0.5: 3]a =
0 0.5000 1 1.5000 2 2.5000 3
Based on the above input, a formula of b=3 sin a is computed as>> b = 3*sin(a)b =
0 1.4383 2.5244 2.9925 2.7279 1.7954 0.4234
length function can be used to determine the number of values in array a>> c = length (a) or >> c = length [0:0.5:3]c =
7
More on Array(cont.)linespace command can also be used to create a linearly spaced array>> a=linspace(2,4,5)a =
2 2.5 3 3.5 4
which is equivalent to >> a=[2:0.5:4]ans =
2 2.5 3 3.5 4
Polynomial RootsOne of the used of array in MATLAB is to determine the polynomial roots. An array represents the polynomial coefficient starting with the highest power (as the first element). For example the polynomial 6x3 - 4x2 + 7x – 3 would be represented with an array of [6 -4 7 -3]. The roots of this polynomial (the values of x when 6x3 - 4x2 + 7x – 3 =0) can be obtained easily using:
>> a = [6 -4 7 -3]; roots (a) or >> roots ([6 -4 7 -3])a =
0.1004 + 1.0310i0.1004 - 1.0310i0.4659
i.e. the roots are 0.4659 and 0.1004 ± 1.0310i
TEST YOUR UNDERSTANDING
Try the followings:
a) Use MATLAB to determine how many element are there in the array [sin(0):0.1:log10(100)]. Subsequently write a command to generate the value of the 15th element.
b) Using MATLAB, find the roots of polynomial 240 – 76x+4x2+x3
answer : a) 21, 1.4000 b) -12, -4±2i
** produce the same answer by writing the suitable script in m-file
File ManipulationVariables generated within Matlab command windowcan be saved in a *.mat file.
>> save filename.mat or >> save filename
When requried, only selected variables can be saved>> save filename.mat var1 var2 … or>> save filename var1 var2 …
Saved variables is re-loaded using load command>> load filename.mat or >> load filename
Script files, or M-filesMatlab commands can be placed in a text file, called script or M-file. To create M-file choose New from the Filemenu and select M-file. This procedure brings up a text editor window.Commands within the M-file have access to all variables in the Matlab workspace, and all variables created in the M-file become part of the workspace.