Matlab Lecture Notes (1)
Matlab Lecture Notes (1)
MATLAB
CHAPTERS
We will focus on the foundations of MATLAB, once these are well understood,
Advanced topics might be self taught by using the Help menu or other ...
CHAP I: STARTING WITH
MATLAB
CONTENT
1. STARTING MATLAB (MATLAB WINDOWS)
2. WORKING IN THE COMMAND WINDOW
3. ARITHMETIC OPERATIONS WITH SCALARS (Order of Precedence, Using MATLAB
as a Calculator)
4. DISPLAY FORMATS
5. ELEMENTARY MATH BUILT-IN FUNCTIONS
6. DEFINING SCALAR VARIABLES ( The Assignment Operator; Rules About Variable
Names; Predefined Variables and Keywords )
7. USEFUL COMMANDS FOR MANAGING VARIABLES
8. SCRIPT FILES ( Notes About Script Files; Creating and Saving a Script File;
Executing a Script File ;Current Folder )
9. EXAMPLES OF MATLAB APPLICATIONS
Chapter 1: Starting with MATLAB
• Purpose:
describe the characteristics of the different windows.
shows how to use MATLAB for arithmetic operations
Introduce script files ( how to write, save, and execute)
1.1 STARTING MATLAB
Editor Window Creates and debugs script and func- tion files.
Workspace Window Provides information about the vari- ables that are
stored.
Current Folder Window Shows the files in the current folder.
Example of a Figure Window
Example of an Editor Window
Example of a Help Window
Working in the Command
Window
• To type a command, the cursor must be placed next to the
command prompt (>> )
• Once a command is typed and the Enter key is pressed, the
command is executed.
• Several commands can be typed in the same line. This is done
by typing a comma between the commands.
• It is not possible to go back to a previous line that is displayed
in the Command window, make a correction, and then re-
execute the command.
Working in the Command
Window
1.2 MAKING A CORRECTION
• A previously typed command can be recalled to the command
prompt with the up-arrow key (↑ ).
• The down-arrow key (↓) can be used to move down the list of
previously typed commands.
• If a command is too long to fit in one line, it can be continued
to the next line by typing three periods … (called an ellipsis) and
pressing the Enter key. The continuation of the command is
then typed in the new line
The semicolon ( ; )
• Normally when a command is typed in the Command Window and
the Enter key is pressed, the command is executed. Any output that
the command generates is displayed in the Command Window.
• If a semicolon ( ; ) is typed at the end of a command, the output of
the command is not displayed. Typing a semicolon is useful when the
result is obvious or known, or when the output is very large.
• If several commands are typed in the same line, the output from any
of the commands will not be displayed if a semicolon instead of a
comma is typed between the commands.
Typing %
• When the symbol % (percent) is typed at the beginning of a line, the
line is designated as a comment.
• This means that when the Enter key is pressed the line is not
executed.
• The % character followed by text (comment) can also be typed after a
command (in the same line). This has no effect on the execution of
the command.
• Usually there is no need for comments in the Command Window.
Comments, however, are frequently used in a program to add
descriptions or to explain the program (in editor file).
The clc command
• The clc command (clc and press Enter) clears the Command Window.
• After typing in the Command Window for a while, the display may
become very long.
• Once the clc command is executed, a clear window is displayed.
• The command does not change anything that was done before.
• For example, if some variables were defined previously, they still exist
and can be used.
• The up-arrow key can also be used to recall commands that were
typed before.
1.3 ARITHMETIC OPERATIONS
WITH SCALARS
• Numbers can be used in • The symbols of arithmetic
arithmetic calculations directly operations are:
(as with a calculator).
• It should be pointed out here
that all the symbols except the
left division are the same as in
most calculators.
• For scalars, the left division is
the inverse of the right
division.
Order of Precedence
• MATLAB executes the calculations according to the order of precedence
displayed below.
The array is a fundamental form that MATLAB uses to store and manipulate
data. An array is a list of numbers arranged in rows and/or columns
rA = 2i + 4j +5k
where i, j, and k are unit vectors in the direction of the x, y, and z axes, respectively.
The numbers 2, 4, and 5 can be used to define a row or a column vector.
Row vector: To create a row vector type the elements with a space or a comma
between the elements inside the square brackets.
Column vector: To create a column vector type the left square bracket [ and
then enter the elements with a semicolon between them, or press the Enter
key after each element. Type the right square bracket] after the last element.
Example Table 2-1: Population data
Year 1984 1986 1988 1990 1992 1994 1996
Population (millions) 127 130 136 145 158 178 211
• A vector with n elements that are linearly (equally) spaced in which the first
element is xi and the last element is xf can be created by typing the linspace
command (MATLAB determines the correct spacing):
(cont’d)
• When the number of elements is omitted, the default is 100. Some
examples are:
>> va=linspace(0,8,6) 6 elements, first element 0, last element 8.
va =
0 1.6000 3.2000 4.8000 6.4000 8.0000
>> vb=linspace(30,10,11) 11 elements, first element 30, last element 10.
vb =
30 28 26 24 22 20 18 16 14 12 10
>> u=linspace(49.5,0.5) First element 49.5, last element 0.5.
When the number of elements is
u = omitted, the default is 100.
Columns 1 through 10
Rows of a matrix can also be entered as vectors using the notation for creating vectors with
constant spacing, or the linspace command.
For example
In this example the first two rows were entered as vectors using the notation of constant
spacing, the third row was entered using the linspace command, and in the last row the
elements were entered individually.
(cont’d)
2.2.1. The zeros, ones and, eye Commands
The zeros(m,n), ones(m,n), and eye(n) commands can be used to
create matrices that have elements with special values. The
zeros(m,n) and the ones(m,n) commands create a matrix with m rows
and n columns in which all elements are the numbers 0 and 1,
respectively. The eye(n) command creates a square matrix with n
rows and n columns in which the diagonal elements are equal to 1
and the rest of the elements are 0. This matrix is called the identity
matrix. Examples are:
(cont’d)
1. All variables in MATLAB are arrays. A scalar is an array with one
element, aVARIABLES
NOTES ABOUT vector is an array with one row or one column of
IN MATLAB
This is useful when there is a need to redefine only some of the elements, when
specific elements are to be used in calculations, or when a subgroup of the
elements is used to define a new variable.
2.4.1. Vector
The address of an element in a vector is its position in the row (or column). For a vector
named ve, ve(k) refers to the element in position k. The first position is 1. For example,
if the vector ve has nine elements:
(cont’d)
2.4.2. Matrix
The address of an element in a matrix is its position, defined by
the row number and the column number where it is located. For
a matrix assigned to a variable ma, ma(k,p) refers to the
element in row k and column p.
Adding elements to a
(cont’d)
2.7. ADDING ELEMENTS TO EXISTING VARIABLES
Adding elements to a
Rows and/or columns Matrix:
can be added to an existing matrix by assigning values to the new
rows or columns. This can be done by assigning new values, or by appending existing
variables. This must be done carefully since the size of the added rows or columns must
fit the existing matrix. Examples are:
ADDING ELEMENTS TO EXISTING VARIABLES
2.
Test your
understanding
Chapter 1 & 2
T1. 1-1 MATLAB as a calculator
EXAMPLE 1.1–1:Volume of a Circular
Cylinder
• The volume of a circular cylinder of height h and radius r is given by
V=πr2h. A particular cylindrical tank is 15 m tall and has a radius of 8
m. We want to construct another cylindrical tank with a volume 20
percent greater but having the same height. How large must its radius
be?
Hint: First solve the cylinder equation for the radius r. This gives
Solution
• We can also express the vector as a row vector which has a horizontal
arrangement,
• or as column vector, which has a vertical arrangement.
Creating Vectors in MATLAB
• Create P=5i + 7j +2k
1. As a row vector,
2. As a column vector.
3. Try to use the colon operator (:) and linspace function to generate
two different large vector of your own.
4. Check the length of each vector.
Polynomial Roots
• We can describe a polynomial in MATLAB with an array whose
elements are the polynomial’s coefficients, starting with the
coefficient of the highest power of x.
• The polynomial would be represented as the array
.
• To find the roots of
• We can represent it in Matlab and use the function roots as
Two-Dimensional Arrays
• An array having rows and columns is a two-dimensional array that is
sometimes called a matrix.
• We refer to the size of an array by the number of rows and the number
of columns.
For example, an array with 3 rows and 2 columns is said to be a 3x2 array.
• If the matrix has many elements, you can press Enter and continue
typing on the next line.
Test your understanding
Plotting with MATLAB
Mathematical Operations with
Matrix
Rows and Columns
Indexing
Array Addressing
Array Addressing
Matrices and the Transpose
Operation
Matrix addition and subtraction
Matrix addition and subtraction are identical to element-by-element
addition and subtraction.
However, matrix multiplication and division are not the same as element-
by element multiplication and division
Array Multiplication (u.*w)
• The vector dot product (u . w) of the vectors u and w is a scalar found
by :
• Example: The table below gives the speed of an aircraft on each leg of a
certain trip and the time spent on each leg. Compute the miles traveled on
each leg and the total miles traveled.
• The miles traveled on each leg of the trip are found using element by
element multiplication (S.*t).
• To find the total miles traveled, we use the matrix product (S*t’).
Test your understanding
Exercise 1: Use MATLAB to compute the following vectors:
• You can use the left division operator (\) in MATLAB to solve sets of
linear algebraic equations. For example, consider the set
• Many applications in physics and engineering use the cross product and
dot product; for example, calculations to compute moments and force
components use these special products.
• To compute the component of the force F along the direction given by
the vector r, you type dot(F,r).
• To compute the moment M with respect to a reference point O due to
the force F, we use M=r xF, where r is the position vector from the point
O to the point where the force F is applied.
• In MATLAB, to find the moment you type M = cross(r,F) .
Polynomial Operations Using
Arrays
• MATLAB has some convenient tools for working with polynomials.
• We can describe a polynomial in MATLAB with a row vector whose elements are the
polynomial’s coefficients, starting with the coefficient of the highest power of x.
• The answer (y) is a column array containing the values -2, -5, -5.
Matlab function poly(r)
Polynomial Addition and
Subtraction
x1 = 0:0.01:2;
f1 = 10*ones(size(x1));
x2 = 2.01:0.01:4.99;
f2 = zeros(size(x2));
x3 = 5:0.01:7;
f3 = -3*ones(size(x3));
f = [f1, f2, f3];
x = [x1, x2, x3];
plot(x,f),xlabel(‘x’),ylabel(‘y’
% plot(x1,f1,x2,f2,x3,f3)
Plotting with MATLAB
• MATLAB contains many powerful functions for easily creating plots of several
different types, such as rectilinear, logarithmic, surface, and contour plots.
• As a simple example, for 0 ≤x ≤7, the code is :
x = 0:0.01:7;
y = 3*cos(2*x);
plot(x,y),xlabel('x'),ylabel('y')
clear all
clc
x = 0:0.01:5;
y = 2*sqrt(x);
z = 4*sin(3*x);
plot(x,y,x,z),xlabel('x'),gtext('y'),gtext('z')
• The gtext function places the text at the point on the plot where the cursor
is located when you click the left mouse button
• Use the gtext function to place the labels y and z next to the appropriate
curves
Some MATLAB plotting commands
Test Your Understanding
DEBUGGING
• Debugging is the process of finding and removing the “bugs,” or errors,
in a program. MATLAB usually detects the more obvious errors and displays a
message describing the error and its location.
% Input Variable:
% t nal = nal time (in seconds)
%
% Output Variables:
% t = array of times at which speed is computed (seconds)
% v = array of speeds (meters/second)
%
% Parameter Value:
g = 9.81; % Acceleration in SI units
%
% Input section:
tfinal = input(‘Enter the nal time in seconds:’);
%
% Calculation section:
dt = tfinal/500;
t = 0:dt:tfinal; % Creates an array of 501 time values.
v = g*t;
%
% Output section:
plot(t,v),xlabel(‘Time (seconds)’),ylabel(‘Speed (meters/second)’)
Input and Output Functions
MATLAB Help System
• To explore the more advanced features of MATLAB, you will need to know how to
use effectively the MATLAB Help System.
• MATLAB has these options to get help:
1. Function Browser providing quick access to the documentation for the MATLAB
function.
To activate the Function Browser, select the fx icon to the left of the prompt.
1. Help Browser helps you to find information and view online documentation.
To open the Help Browser,click the question mark button in the toolbar.
1. Help Functions ( help, lookfor, and doc functions can be used to display syntax
information for a specified function.
2. Other Resources For additional help.
Help Functions (help …)
• The help Function The help function is the most basic way to
determine the syntax and behavior of a particular function.
• For example, typing help log10 in the Command window produces the
following display:
Help Functions (lookfor …)
• The lookfor Function The lookfor function allows you to search for
functions on the basis of a keyword.
For example, MA TLAB does not have a function named sine. Use
(lookfor …) rather than using (help…)
Help Functions (doc …)
• Typing (doc …) displays the documentation for the MATLAB function
or toolboox.
MATLAB Help functions
Problem-Solving Methodologies
Study well Pages (31-46) in the book entitled “Intro to Matlab
Programming for engineers”.
Functions.
• A function is a piece of computer code that accepts an input argument from
the user and provides output to the program.
• Functions enable us to avoid rewriting the computer code for calculations that
are performed frequently.
• For example, a function that calculates y as the sine of a x degrees is:
Output Input
Function Name
Introduction
• Both built-in MATLAB functions and user-defined functions have the
same structure.
• Each consists of a name, user-provided input(s), and calculated output (s).
User-defined functions are created in M-files. Each must start with a function definition line that
contains:
Call the DR function, and use it to find radians Call the DR function, and use it to find degrees
radians = DR(degrees); degrees = RD(radians) ;
Comments
• As with any computer program, you should comment your code liberally so that it is easy to
follow
• Function comments at the first line are displayed when you use the help feature. For example:
function [] = star( )
theta = pi/2:0.8*pi:4.8*pi; function flower
r = ones(1,6); t = 0 : .01 : 2 * pi;
polar(theta,r) polar(t, sin(2 * t) .* cos(2 * t), '--r');
end end
• The variables a, x, y, and output are local variables. They can be used for
additional calculations inside the g function, but they are not stored in the
workspace.
• To confirm this, clear the workspace and the command window and then call the g
function:
Global Variables
• The global command alerts the function to look in the workspace for the
value of G.
• This approach allows you to change the value of G easily.
Solved Exercises
Write a function called circle that takes a scalar input r. It needs to
return an output called area that is the area of a circle with radius r and
a second output, cf that is the circumference of the same circle. You are
allowed to use the built-in function pi. In fact, you need to use it to get
the value of π as accurately as possible.
Write a function called even_index that takes a matrix, M, as input
argument and returns a matrix that contains only those elements of M
that are in even rows and columns. In other words, it would return the
elements of M at indices (2,2), (2,4), (2,6), …, (4,2), (4,4), (4,6), …, etc.
Note that both the row and the column of an element must be even to
be included in the output. The following would not be returned: (1,1),
(2,1), (1,2) because either the row or the column or both are odd. As an
example, if M were a 5-by-8 matrix, then the output must be 2-by-4
because the function omits rows 1, 3 and 5 of M and it also omits
columns 1, 3, 5, and 7 of M.
Write a function called flip_it that has one input argument, a row
vector v, and one output argument, a row vector w that is of the same
length as v. The vector w contains all the elements of v, but in the exact
opposite order. For example, is v is equal to [1 2 3] then w must be
equal to [3 2 1]. You are not allowed to use the built-in function flip.
Write a function called top_right that takes two inputs: a matrix N and
a scalar non-negative integer n, in that order, where each dimension of
N is greater than or equal to n. The function returns the n-by-n square
array at the top right corner of N
Write a function called peri_sum that computes the sum of the elements of
an input matrix A that are on the “perimeter” of A. In other words, it adds
together the elements that are in the first and last rows and columns. Note
that the smallest dimension of A is at least 2, but you do not need to check
this
Comptuter Programming
• The MATLAB interactive mode is very useful for simple problems, but more complex
problems require a script file.
• Such a file is called a computer program, and writing such a file is called programming.
• The usefulness of MATLAB is greatly increased by the use of decision making or control
structures (program flow)
• MATLAB can also repeat calculations a specified number of times or until
some condition is satisfied (using Loops)
• This feature enables engineers to solve problems of great complexity or requiring
numerous calculations.
Algorithms and Control
Structures
• An algorithm is an ordered sequence of precisely defined instructions that
performs some task in a definite amount of time.
• There are three categories of algorithmic operations:
1. Sequential operations: These instructions are executed in order.
2. Conditional operations: These control structures first ask a question to be
answered with a true/false answer and then select the next instruction based
on the answer.
3. Iterative operations (loops): These control structures repeat the execution
of a block of instructions.
Conditional Statements
o A conditional statement is a command that allows MATLAB to make a
decision of whether to execute a group of commands that follow the
conditional statement, or to skip these commands.
o In a conditional statement, a conditional expression is stated. If the
expression is true, a group of commands that follow the statement
are executed.
o If the expression is false, the computer skips the group of commands
also called brock of commands
If - statement
• The most common selection construct is the If statement.
• Let us introduce it with an example:
function guess_my_number(x)
if x == 2
fprintf('Congrats! You guessed my number.\n');
end
Formulation of if - statement
Begins with control statement: if keyword followed by a logical
condition
In between: block of statements to be executed if and
only if condition is true
Ends with statement: end
if logical expression
block
end
Schematic of an if - statement
function ultimate_question_nested(x)
if x == 42
fprintf('Wow! You answered the question.\n');
else
if x < 42
fprintf('Too small. Try again.\n');
else
fprintf('Too big. Try again.\n');
end
Here is an other version of Nested if
statement
function ultimate_question_nested(x)
if x == 42
fprintf('Wow! You answered the question.\n');
else
if x < 42
fprintf('Too small. Try again.\n');
else
fprintf('Too big. Try again.\n');
end
end
Polymorphic functions
• Functions that behave differently based on
◦ Number of input or output arguments
◦ Type of input or output arguments
• Many built-in functions are polymorphic (sqrt, max, size, plot, etc.)
o How do we make our functions polymorphic?
Number of inputs and outputs
• We can use two built-in functions:
◦ nargin: returns the number of actual input
arguments that the function was called with
◦ nargout: returns the number of output arguments
that the function caller requested
Multiplication table
(Illustrative example for the above
notions)
function [table summa] = multable(n, m)
o The function multable returns an n-by-m
multiplication table in the output argument table
o Optionally, it can return the sum of all elements
in the output argument summa
o If m is not provided, it returns and n-by-n matrix
Multiplication table
function [table summa] = multable(n, m)
if nargin < 1
error('must have at least one input argument');
end
if nargin < 2
m = n;
elseif ~isscalar(m) || m < 1 || m ~= fix(m)
error('m needs to be a positive integer');
end
if ~isscalar(n) || n < 1 || n ~= fix(n)
error('n needs to be a positive integer');
end
table = (1:n)' * (1:m);
if nargout == 2
summa = sum(table(:));
switch-case structure
• The switch-case statement is another method that can be used to
direct the flow of a program. It provides a means for choosing one
group of commands for execution out of several possible groups
• After the group of commands associated with the first matching case
are executed, the program skips to the end statement.
X=[1:3;4:6;7:9];
choose= input('To make the diagonal of X equal to zero, choose between
the 2 methods.(1/2)');
switch choose
case 1
% method 1
Y= X-X.*eye(3);
disp('X=')
disp (X)
disp('Y=')
disp(Y)
case 2
% method 2
X(logical(eye(3)))=0;
disp('X=')
disp (X)
disp('Y=')
disp(Y)
end
Loops
• A loop is another method to alter the flow of a computer program.
• In a loop, the execution of a command, or a group of commands, is repeated
several times consecutively.
• Each round of execution is called a pass.
• MATLAB has two kinds of loops.
1. for-end loops (the number of passes is specified when the loop
starts).
2. while-end loops (the number of passes is not known ahead of time, and the
looping process continues until a specified condition is satisfied.
3. Both kinds of loops can be terminated at any time with the break command
The structure of a for-end loop
Illustrative example
total = 0;
for n = 1:5
total = total + n;
end
fprintf('total equals %d\n',total);
while-end Loops
• while-end loops are used in situations when looping is needed but the
number of passes is not known in advance.
• In while-end loops the number of passes is not specified when the
looping process starts. Instead, the looping process continues as long
as a stated condition is satisfied.
.
The break command
• When inside a loop (for or while), the break command terminates the
execution of the loop (the whole loop, not just the last pass). When the
break command appears in a loop, MATLAB jumps to the end command
of the loop and continues with the next command (it does not go back to
the for command of that loop).
• If the break command is inside a nested loop, only the nested loop is
terminated
Illustrative example
for k = 1:10
x = 50 - k^2;
if x < 0
break
end
y = sqrt(x)
end
% The program execution jumps to here
% if the break command is executed.
The continue command
• The continue command can be used inside a loop (for or while) to
stop the present pass and start the next pass in the looping process.
• The continue command is usually a part of a conditional statement.
When MATLAB reaches the continue command, it does not execute the
remaining commands in the loop, but skips to the end command of the
loop and then starts a new pass.
Illustrative example
x = [10,1000,-10,100];
y = NaN*x;
for k = 1:length(x)
if x(k) < 0
continue
end
kvalue(k) = k;
y(k) = log10(x(k));
end
kvalue
y
1. Write a script file to compute the sum of the first 15 terms in the series -2k, k= 1, 2, 3, . . . ,
15.
2. Write a script file to plot the function
3. Write a script file to determine the number of terms required for the sum of the series
series -2k, k= 1, 2, 3, . . . , to exceed 10 000. What is the sum for this many terms?
• Consider the variable-mass rocket treated above. Write a program to
determine how long it takes for the rocket to reach 40 000 ft if the
burn time is 50 sec