0% found this document useful (0 votes)
9 views

Matlab Lecture Notes (1)

The document introduces MATLAB, a high-level programming language developed by MathWorks, primarily used for numerical computation and engineering applications. It covers fundamental topics such as starting MATLAB, creating arrays, performing mathematical operations, and using script files. The document emphasizes the importance of understanding basic concepts before moving on to advanced topics.

Uploaded by

sabbathshema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Matlab Lecture Notes (1)

The document introduces MATLAB, a high-level programming language developed by MathWorks, primarily used for numerical computation and engineering applications. It covers fundamental topics such as starting MATLAB, creating arrays, performing mathematical operations, and using script files. The document emphasizes the importance of understanding basic concepts before moving on to advanced topics.

Uploaded by

sabbathshema
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 181

Introduction to

MATLAB
CHAPTERS

I. Starting with Matlab


II. Creating Arrays
III. Mathematical operations with
arrays
IV. Using Script files and Managing
data
V. User-Defined Functions and
Function Files
VI. Two dimensional Plots
VII.Programming with Matlab
Introduction
• MATLAB is developed by MathWorks. The name MAT- LAB stands for MATrix LABoratory.
Because its basic data element is a matrix (array).
• A high-level Programming language software used for Numerical computation.
• Most of the computational math work, algorithms, Complex Engineering problems,
Graphs and system design equations can be done with MATLAB.
• It also has other great features of designing a control system using it’s Simulink library.
• As a computational tool MATLAB is widely used in almost all Engineering fields, such as
solving differential equations, calculating integration, solving polynomials, performing
transforms such as Fourier, Laplace, Inverse Laplace and to create different plots.

 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

• It is assumed that the software is installed on the computer, and that


the user can start the program.
• To start MATLAB on a MS Windows system, double-click on the
MATLAB icon. You will then see the MATLAB Desktop.
• The default appearance of the desktop is shown in next slide with Five
windows.
The default view of MATLAB
desktop
MATLAB windows with their
Purpose
Window Purpose
Command Window Main window, enters variables, runs programs.

Figure Window Contains output from graphic com- mands.

Editor Window Creates and debugs script and func- tion files.

Help Window Provides help information.


Command History Win- dow Logs commands entered in the Com- mand Window.

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.

• This order is the same as used in most calculators.


MATLAB as a Calculator
• This is done in the Command
Window by typing a mathematical
expression and pressing the Enter
key.
• MATLAB calculates the expression
and responds by displaying ans =
followed by the numerical result of
the expression in the next line.
Complex Number Operations
Test Your Understanding
1.4 DISPLAY
FORMATS

• MATLAB has several other


formats for displaying numbers.
• Details of these formats can be
obtained by typing help format
in the Command Window.
• The format in which numbers
are displayed does not affect
how MATLAB computes and
saves numbers.
1.5 ELEMENTARY MATH BUILT-IN
FUNCTIONS
• MATLAB has a very large library of
built-in functions.
• A function has a name and an
argument in parentheses.
• For example, the function that
calculates the square root of a
number is sqrt(x).
• Its name is sqrt,
• And the argument is x.
Continued…
• Some commonly used elementary MATLAB mathematical built-in
functions are given:
Continued…
• Some commonly used elementary MATLAB mathematical built-in
functions are given:
Continued…
• Some trigonometric math functions are given:
Continued…
• Some rounding function are given:
1.6 DEFINING SCALAR VARIABLES
• A variable is a name made of a letter or a combination of several letters
(and digits) that is assigned a numerical value.
• Once a variable is assigned a numerical value:
 it can be used in mathematical expressions,
 it can also be used in functions, in any MATLAB statements.
A variable is actually a name of a memory location. When a new
variable is defined, MATLAB allocates an appropriate memory space
where the variable’s assignment is stored.
If the variable is assigned to a new value the content of the memory
location is replaced.
Assignment Operator
• In MATLAB the ‘‘= ’’ sign is called the assignment operator.
• The assignment operator assigns a value to a variable.
using semicolons
• If a semicolon is typed at the end of the command, then when the
Enter key is pressed, MATLAB does not display the variable with its
assigned value (the variable still exists and is stored in memory).
• If a variable already exists, typing the variable’s name and pressing
the Enter key will display the variable and its value in the next two
lines.
• As an example, the last demonstration is repeated below using
semicolons.
using semicolons
• Several assignments can be typed in the same line. The assignments
must be separated with a comma (spaces can be added after the
comma).
• When the Enter key is pressed, the assignments are executed from
left to right and the variables.
Defining Scalar Variables
Rules About Variable Names
A variable can be named according to the following rules:
• Must begin with a letter.
• Can be up to 63 characters long.
• Can contain letters, digits, and the underscore character.
• Cannot contain punctuation characters (e.g., period, comma, semicolon).
• MATLAB is case-sensitive: it distinguishes between uppercase and lowercase
letters. For example, AA, Aa, aA, and aa are the names of four different variables.
• No spaces are allowed between characters (use the underscore where a space is
desired).
• Avoid using the name of a built-in function for a variable (i.e., avoid using cos,
sin, exp, sqrt, etc.). Once a function name is used to for a variable name, the
function cannot be used
Predefined Variables and Keywords
• There are 20 words, called keywords, that are reserved by MATLAB for
various purposes and cannot be used as variable names.
• These words are:
break case catch classdef continue else elseif end for
function global if otherwise parfor persistent return
spmd switch try while
The keywords can be displayed by typing the command iskeyword.
.
1.7 USEFUL COMMANDS FOR
MANAGING VARIABLES
• When these commands are typed in the Command Window and the
Enter key is pressed, they perform a task as specified below.
Testing your
understandin
g
1.8 SCRIPT FILES
• So far all the commands were typed in the Command Window and were
executed when the Enter key was pressed.
• using the Command Window to execute a series of commands—especially if they
are related to each other (in a program)—is not convenient and may be difficult
or even impossible. Because the commands in the Command Window cannot be
saved and executed again.
• In addition, the Command Window is not interactive. This means that every time
the Enter key is pressed only the last command is executed, and everything
executed before is unchanged.
• If a change or a correction is needed in a command that was previously executed
and the result of this command is used in commands that follow, all the
commands have to be entered and executed again.
Continued…
• A different (better) way of executing commands with MATLAB is first
to create a file with a list of commands (program), save it, and then
run (execute)the file.
• When the file runs, the commands it contains are executed in the
order that they are listed.
• If needed, the commands in the file can be corrected or changed and
the file can be saved and run again.
Files that are used for this purpose are called script files.
Notes About Script Files
Script files
Script files
• Once the window is open, the commands of the script file are
typed line by line. MATLAB automatically numbers a new line
every time the Enter key is pressed.
• Before a script file can be executed it has to be saved. This is
done by clicking Save in the Toolstrip and selecting Save As...
from the menu that opens. When saved, MATLAB adds the
extension .m to the name.
Running (Executing) a Script File
• A script file can be executed either directly from the Editor Window
by clicking:
on the Run icon
or by typing the file name in the Command Window and then
pressing the Enter key.
• For a file to be executed, MATLAB needs to know where the file is
saved.
• The file will be executed if the folder where the file is saved is the
current folder of MATLAB or if the folder is listed in the search path,
as explained next.
Changing file directory
• The Current Folder can be changed by choosing the drive and the
folder where the file is saved.
Sample Problem 1: Trigonometric
identity
Sample Problem 2: Heat transfer
Steps in engineering problem
solving
1. Understand the purpose of the problem.
2. Collect the known information.
3. Determine what information you must find.
4. Draw a sketch and label any necessary variables.
5. Determine which fundamental principles are applicable.
6. Think generally about your proposed solution approach and consider other
approaches before proceeding with the details.
7. Label each step in the solution process.
8. If you solve the problem with a program, Checking the dimensions and units.
9. Perform a “reality check” on your answer. Does it make sense? Estimate the
range of the expected result and compare it with your answer.
Chapter 2: Creating Arrays

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

One-dimensional Array (Vector) : A Two-dimensional Array (Matrix):


row or a column of numbers. A collection of numbers arranged
in rows and columns
2.1. CREATING A ONE-DIMENSIONAL ARRAY (VECTOR)

The position of point A can be expressed in terms of a position vector:

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.

Figure 2-1: Position of a point.


(cont’d)
The vector is created by typing the elements (numbers) inside square brackets [ ].

variable_name = [type vector elements]

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

Tutorial 2-1: Creating vectors from given data.


(cont’d)

Creating a vector with constant spacing by specifying the first term,


the spacing, and the last term:
Some examples are:
(cont’d)
• Creating a vector with linear (equal) spacing by specifying
the first and last terms, and the number of terms

• 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

49.5000 49.0051 48.5101 48.0152 47.5202 47.0253


46.5303 46.0354 45.5404 45.0455
............ 100 elements are displayed.
Columns 91 through 100
4.9545 4.4596 3.9646 3.4697 2.9747 2.4798
1.9848 1.4899 0.9949 0.5000
>>
(cont’d)
2.2. CREATING A TWO-DIMENSIONAL ARRAY (MATRIX).

Tutorial 2-2: Creating matrices.


(cont’d)

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

elements, and a matrix is an array with elements in rows and


columns.

2. The variable (scalar, vector, or matrix) is defined by the input when


the variable is assigned. There is no need to define the size of the
array (single element for a scalar, a row or a column of elements
for a vector, or a two-dimensional array of elements for a matrix)
before the elements are assigned.

3. Once a variable exists—as a scalar, vector, or matrix—it can be


changed to any other size, or type, of variable. For example, a
scalar can be changed to a vector or a matrix; a vector can be
changed to a scalar, a vector of different length, or a matrix; and a
matrix can be changed to have a different size, or be reduced to a
vector or a scalar. These changes are made by adding or deleting
elements.
(cont’d)
2.4. THE TRANSPOSE OPERATOR
The transpose operator is applied by typing a single quote ’ following the variable to be
transposed. Examples are:
(cont’d)
2.4. ARRAY ADDRESSING

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.

As with vectors, it is possible to change the value of just one


element of a matrix by assigning a new value to that element. Also,
single elements can be used like variables in mathematical
expressions and functions. Some examples are:
(cont’d)
It is possible to change the value of just one element of a matrix
by assigning a new value to that element. Also, single elements can
be used like variables in mathematical expressions and functions.
Some examples are:
(cont’d)
2.6. USING A COLON : IN ADDRESSING ARRAYS

A colon can be used to address a range of elements in a vector or a matrix.


For a vector:
 va (:) Refers to all the elements of the vector va (either a row or a column
vector).
 va(m:n) Refers to elements m through n of the vector va. Example:
A(:,n)For
Refers
a to the elements in all the rows of column n of the matrix A.
A(n,:) Refers to the elements in all the columns of row n of the matrix
matrix:
A.
A(:,m:n) Refers to the elements in all the rows between columns m and
n of the matrix A.
A(m:n,:) Refers to the elements in all the columns between rows m and
n of the matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and columns p
through q
of the matrix A.
(cont’d)
(cont’d)
It is possible, also, to select only specific elements, or specific rows and columns of
existing variables to create new variables. This is done by typing the selected elements or
rows or columns inside brackets, as shown below:
(cont’d)
2.7. ADDING ELEMENTS TO EXISTING VARIABLES

Adding elements to a vector:


Elements can be added to an existing vector by assigning values to the new ele-ments. For
example, if a vector has 4 elements, the vector can be made longer by assigning values to
elements 5, 6, and so on. If a vector has n elements and a new value is assigned to an
element with an address of n+2 or larger, MATLAB assigns zeros to the elements that are
between the last original element and the new element.
Elements can also be added to a vector by appending existing vectors. Two examples are:

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

If a matrix has a size of and a new value is assigned to an


element with an address beyond the size of the matrix, MATLAB
increases the size of the matrix to include the new element. Zeros
are assigned to the other elements that are added. Examples:
(cont’d)
2.7. DELETING ELEMENTS
An element, or a range of elements, of an existing variable can be
deleted by re- assigning nothing to these elements. This is done by using
square brackets with nothing typed in between them. By deleting
elements, a vector can be made shorter and a matrix can be made
smaller. Examples are:
(cont’d)
2.9. BUILT-IN FUNCTIONS FOR HANDLING ARRAYS
MATLAB has many built-in functions for managing and handling arrays.
Some of these are listed below:
Function Description Example
length(A) Returns the number of ele- >> A=[5 9 2 4];
ments in the vector A. >> length(A)
ans =
4
size(A) Returns a row vector [m,n], where m and n >> A=[6 1 4 0 12; 5
are the size 19 6 8 2]
of the array A. A =
6 1 4 0 12
5 19 6 8 2
>> size(A)
ans =
2 5
reshape(A, Creates a m by n matrix from >> A=[5 1 6; 8 0 2]
m,n) the elements of matrix A. The elements are A =
taken column after column. Matrix A must 5 1 6
have m times n elements. 8 0 2
>> B =
reshape(A,3,2)
B =
5 0
8 6
1 2
(cont’d)
2.9. BUILT-IN FUNCTIONS FOR HANDLING ARRAYS
MATLAB has many built-in functions for managing and handling arrays.
Some of these are listed below:
(cont’d)
2.9. Sample Problems
1.Create a 6x6 matrix in which the middle two rows and the
middle two columns are 1s and the rest of the entries are 0s.

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

Assign values to the variables r and h.


Then compute the volume of the original cylinder and increase the
volume by 20 percent. Finally, we solve for the required radius.
>>r = 8;
>>h = 15;
>>V = pi*r^2*h;
>>V = V + 0.2*V;
>>r = sqrt(V/(pi*h))
r=
8.7636
Note the importance of ; sign.
Note how precedence applies to the line V =pi*r^2*h;.
It is equivalent to V = pi*(r^2)*h;.
Note also how we use the MATLAB built-in constant pi.
T1.1–2 Complex number in Matlab
One- and Two-Dimensional Numeric
Arrays
• We can represent the location of a point in three-dimensional space
by three Cartesian coordinates x, y, and z

• 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.

We sometimes represent a matrix M, and indicate one of its elements Mij


Creating Matrices
The most direct way to create a matrix is to type the matrix row by
row, separating the elements in a given row with spaces or commas
and separating the rows with semicolons.
Brackets are required. For example, typing

• 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.

The corresponding matrix elements are summed or subtracted.

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 :

• It can be thought of as the perpendicular projection of u onto w.


algebraically computed from |u||w| cos θ, where θ is the angle
between the two vectors and |u|, |w| are the magnitudes of the
vectors.
Matrix Multiplication
• This is different from element by element product.
Matrix-Matrix Multiplication
The number of columns in A must equal the number of rows in B.
ARRAY MULTIPLICATION
Array Multiplication (s.*t) and matrix multiplication (s*t’)

• 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:

To get an (Answer: -6.) which multiplication are you using?

• Exercise 2: use MATLAB to show that


The General Matrix
Multiplication Case
Array Division
Matrix division
• Matrix division is a complicated concept in linear algebra.
• Matrix division uses both the right and left division operators, / and \.
• Application of left division will be used to find the solution of sets of
linear algebraic equations.
LEFT DIVISION and Linear Algebraic Equations

• You can use the left division operator (\) in MATLAB to solve sets of
linear algebraic equations. For example, consider the set

• The solution is obtained by typing A\B. >>A = [6,12,4;7,-2,3;2,8,-9];


>>B = [70;5;64];
• The left division method works when >>Solution = A\B
Solution =
the equation set has a unique solution 35
-2

The solution is x =3, y =5, and z =2


Test Your Understanding
Matrix Exponentiation

• Raising a matrix to a power is equivalent to repeatedly multiplying the


matrix by itself, for example, A2 = AA.
• This process requires the matrix to have the same number of rows as
columns; that is, it must be a square matrix.
• MATLAB uses the symbol ^ for matrix exponentiation. To find A2, type
A^2.
Special Products

• 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.

 For example, to obtain the roots of


Type y = roots([1,12,45,50]).

• The answer (y) is a column array containing the values -2, -5, -5.
Matlab function poly(r)
Polynomial Addition and
Subtraction

The result is h = [9,1,2,9], which corresponds to h(x)=9x3+x2+2x+9


Subtraction is done in a similar way.
Polynomial Multiplication and
Division
• To multiply a polynomial by a scalar, simply multiply the coefficient
array by that scalar.
• For example, 5h(x) is represented by [45,5,10,45] with
h(x)=9x3+x2+2x+9
Polynomial functions
Illustrative example
Plotting Polynomials
• The polyval(a,x) function evaluates a polynomial at specified values of
its independent variable x, which can be a matrix or a vector.
• For example, to plot the polynomial f(x)=9x3-3x+7 for -2≤x≥5,
• you type:
>>x = -2:0.01:5;
>>f=polyval([9,-5,3,7], x);
>>plot (x,f),xlabel( ‘x’ ),ylabel( ‘f(x) ‘),grid
Test Your Understanding
Special Matrices
Importance of Special Matrices
• Sometimes we want to initialize a matrix to have all zero elements.
The zeros command creates a matrix of all zeros.
• This type of matrix can be useful for applications in which we do not
know the required dimension ahead of time.
• The syntax of the ones command is the same, except that it creates
arrays filled with 1s.
Illustrative Example
• For example, to create and plot the function

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')

• An increment of 0.01 was chosen to generate a large number of x values in order to


produce a smooth curve.
• The function plot(x,y) generates a plot with the x values on the abscissa and the y
values on the ordinate.
• The plot can be printed by selecting Print from the File menu on the graphics
window.
• You can create multiple plots, called overlay plots, by including another set or sets of values
in the plot function.
• For example, to plot the functions and for 0 ≤x ≤5

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.

• Such errors usually fall into one of the following categories:


1. Syntax errors such as omitting a parenthesis or comma, or spelling a command
name incorrectly.
2. Errors due to an incorrect mathematical procedure, called runtime errors
(A common example is division by zero)
Controlling Input and Output
1. The disp function can be used to display the value of a variable but
not its name.
o To display its name use, You enclose the text within single quotes.
Speed=63
disp(‘The predicted speed is:’)
disp(Speed)
Controlling Input and Output
• The input function displays text on the screen, waits for the user to enter something
from the keyboard, and then stores the input in the specified variable.
• For example, the command x = input(‘Please enter the value of
x:’) causes the message to appear on the screen.
• If you type 5 and press Enter, the variable x will have the value 5.
• If you want to store a text input as a string variable, use the other form of the input
command
• Calendar = input(‘Enter the day of the week:’,’s’)
Solved exercise
The speed of a falling object dropped with no initial velocity is given
as a function of time t by , where g is the acceleration due to gravity.
With and 0 ≤t≤tfinal.
We want to compute and plot as a function of t for
, where t final is the final time entered by the user . The script file is
the following
solution
Program Falling_Speed.m: plots speed of a falling object.

% 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:

1. The word function


2. A variable that defines the function output
3. A function name
4. A variable used for the input argument

Example 1: function output = my_function(x)

Example 2: function result = calculation(a)


Converting between degrees and radians

Problem: Engineers usually measure angles in degrees, yet most


computer programs and many calculators require that the input to
trigonometric functions be in radians.

a) Write and test a function DR that changes degrees to radians.


b) Write another function RD that changes radians to degrees.
Note that your functions should be able to accept both scalar and
matrix input.
Solution

function output = DR(x) function output = RD(x)


%This function changes degrees to %This function changes radians to
a) %radians b) %degrees
output = x*pi/180; output = x*180/pi;
end end

 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 results = f(x)


%This function converts seconds to minutes
results = x./60;
end

• Querying the help function from the command window


>> help f
Returns
>>This function converts seconds to minutes
Formal Definition
Multiple Output and Single Input
Example
Write a function finding the values of distance, velocity, and
acceleration at specified times
function [dist, vel, accel] = motion(t)
% This function calculates the distance, velocity, and
% acceleration of a particular car for a given value of t
% assuming all 3 parameters are initially 0.
accel = 0.5 .*t;
vel = t.^2/4;
dist = t.^3/12;
end
Functions with No Input or No
Output
 In some situations no inputs or outputs are required. For example,
consider these 2 functions, which draws a star and a flower in polar
coordinates:
Function star Function flower

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

Note that square bracket and parenthesis might be omitted in case.


Determining the Number of Input and Output
Arguments
• There may be times when you want to know the number of input
arguments or output values associated with a function.
• MATLAB provides two built-in functions for this purpose.
• The nargin (‘…’) and nargout(‘…) functions determine respectively the
number of input or output arguments in either a user-defned function
or a built-in function.
• The name of the function must be specifed as a string, as, for example in:
Local Variables
• Local Variable is a variable that only has meaning inside a program or function.
• The variables used in function M-fles are known as local variables.
• Any variables defined within the function exist only for the function to use. For
example, consider the g function previously described:

function output = g(x,y)


% This function multiplies x and y
together
% x and y must be the same size
matrices
a = x .*y;
output = a;

• 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

• A variable that is available from multiple programs


• Consider the distance function: function result = distance(t)
%This function calculates the
distance a falling object
%travels due to gravity
global G
result = 1/2*G*t.^2;

• 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

General schematic Condition: true Condition: false


if-else-end Structure
o What if we want do something when the condition is false as well?
 we use a new key word: else
 Example
function guess_my_number(x)
if x == 2
fprintf('Congrats! You guessed my number!\n');
else
fprintf('Not right, but a good guess.\n');
end
if – else-end statement paths

General schematic Condition: true Condition: false


Relational Operators
• Note that relation and logical operators appear
inside an if-statements as a condition.
• They can also appear outside an if – statement.
• A relational operator compares two numbers by
determining whether a comparison statement
(e.g., 5 < 8) is true or false.
• If the statement is true, it is assigned a value of
1. If the statement is false, it is assigned a value
of 0.
• Every operational relation returns zero when its
expression is false and one when it expression is
true.
Logical Operator
• A logical operator examines true/false statements and
produces a result that is true (1) or false (0) according to
the specific operator.
• For example, the logical AND operator gives 1 only if both
statements are true.
How to combine logical values?
(Truth Table)
Logical values:
◦ Non-zero: true
◦ Zero: false
Nested if statement
• if-statements can contain other if-statements
• Consider the example with a single if-else if-else 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy