Professional Documents
Culture Documents
AN INTRODUCTORY COURSE ON
MATLAB
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
1.1 Introduction
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)
b. From the Start Menu Programs MATLAB > R2006a > MATLAB
2
NM/May17
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
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,
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
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
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:
4
NM/May17
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
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 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
30 60 90
If you want to perform matrix multiplication, you can: C^2 = 20 40 60
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]
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)
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
7
NM/May17
3.1 Plotting
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
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
Title
Legend
gtext
Y label
Curve
y(x)
X label
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);
-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))
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
%
%
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
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:
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.
To run the function, go to command window and type the following at the command prompt:
change directory
>> cd lesson:\
>> F = 100;
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:
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)
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.
%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
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
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
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
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
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;
fprintf(\nx = %g \n, x)
18
NM/May17
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