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

Lecture1 MATLAB Introduction

Uploaded by

Roman Ayon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture1 MATLAB Introduction

Uploaded by

Roman Ayon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

ME 262

Numerical Analysis Sessional


Introduction to MATLAB

Bangladesh University of Engineering and Technology

6/7/2023
Page 1 of 101
Overview (1)

• Basic M ATLAB Operations


⊲ Starting M ATLAB
⊲ Using M ATLAB as a calculator
⊲ Introduction to variables and functions
• Matrices and Vectors: All variables are matrices.
⊲ Creating matrices and vectors
⊲ Subscript notation
⊲ Colon notation

6/7/2023
Page 2 of 101
Overview (2)

• Additional Types of Variables


⊲ Complex numbers
⊲ Strings
⊲ Polynomials
• Working with Matrices and Vectors
⊲ Some basic linear algebra
⊲ Vectorized operations
⊲ Array operators
• Managing the Interactive Environment
• Plotting

6/7/2023
Page 3 of 101
Installing MATLAB

• BUET students can use authorized licensed MATLAB software by creating an


account using their official email IDs.

•First create an account at ‘mathworks’ in the following link:


https://www.mathworks.com/mwaccount/register?uri=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fwww.mat
hworks.com%2Fproducts%2Fmatlab.html

• Then you can download, install and sign in with your official email ID.
https://www.mathworks.com/downloads/web_downloads/

(Search in google with “download matlab” and you will easily get these links)

6/7/2023
Page 4 of 101
Starting MATLAB

• Double click on the MATLAB icon, or on unix systems type "matlab"


at the command line.
• After startup Matlab displays a command window that is used to
enter commands and display text-only results.
• Enter Commands at the command window:

• Matlab responds to commands by printing text in the command


window, or by opening a figure window for graphical output.

6/7/2023
Page 5 of 101
Matlab Desktop

Recent Directory Menu:


Used to change current
working directory.

Current Directory: change


directories
Command Prompt:
Enter typed commands here.
Text results are displayed here.

This layout can be changed by clicking and dragging any


of the sections from one position to another. Sections
can also be hidden or removed from layout from the
Workspace, layout button at the top
view values of variables in
the workspace

NMM: Interactive Computing with Matlab


6/7/2023
Page 6 of 101
M ATLAB as a Calculator (1)

Enter formulas at the command prompt


>> 2 + 6 - 4 (press return(i.e. enter) after ‘‘4’’)
ans =
4

>> ans/2
ans =
2

6/7/2023
Page 7 of 101
M ATLAB as a Calculator (1)

Define and use variables


>> a = 5
a =
5

>> b = 6
b =
6

>> c =
b/a c =
1.2000

6/7/2023
Page 8 of 101
Built-in Variables

p i ( = π) and ans are a built-in variables

>> p i
ans =
3.141
6

>>
sin(ans/4)
ans =
0.7071

Note: There is no “degrees” mode. All angles are measured in radians.

6/7/2023
Page 9 of 101
Built-in Functions

Many standard mathematical functions, such as sin, cos, log, and


log10, are built-in
>> l o g ( 2 5 6 ) log(x) computes the natural logarithm of x
ans =
5.5452

>> log10(256) log10(x) is the base 10 logarithm


ans =
2.4082

>> log2(256) log2(x) is the base 2 logarithm


ans =
8

6/7/2023
Page 10 of 101
Ways to Get Help

• Use on-line help to request info on a specific function

>> help sqrt

• In M ATLAB version 6 and later the doc function opens the on-line version of the
manual. This is very helpful for more complex commands.

>> doc plot

• Use l o o k f o r to find functions by keywords

>> lookfor functionName

6/7/2023
Page 11 of 101
Online Help (1)

Syntax:
help functionName

Example:
>> help log

produces→

The help function provides a compact summary of how to use a command. Use
the doc function to get more in-depth information.

6/7/2023
Page 12 of 101
Online Help (2)

The help browser opens when you type a doc command:


>> doc plot

6/7/2023
Page 13 of 101
Looking for Functions

Syntax:
lookfor string

searches first line of function descriptions for “string”.


Example:
>> lookfor cosine

produces:

6/7/2023
Page 14 of 101
Strategies for Interactive Computing

• Use the command window for short sequences of calculations


• Later we’ll learn how to build reusable functions for more complex tasks.
• The command window is good for testing ideas and running sequences
of operations contained in functions
• Any command executed in the command window can also be used in a
function.

Let’s continue with a tour of interactive computing.

6/7/2023
Page 15 of 101
Suppress Output with Semicolon (1)

Results of intermediate steps can be suppressed with semicolons.


Example: Assign values to x, y, and z, but only display the value of z in
the command window:
>> x = 5 ;
>> y = s q r t ( 5 9 ) ;
>> z = l o g ( y ) + x^0.25

z =
3.5341

6/7/2023
Page 16 of 101
Suppress Output with Semicolon (2)

Type variable name and omit the semicolon to print the value of a variable
(that is already defined)
>> x = 5 ;
>> y = s q r t ( 5 9 ) ;
>> z = l o g ( y ) + x^0.25
z =
3.5341
>> y
y =
7.6811 ( = l o g ( s q r t ( 5 9 ) ) + 5^0.25 )

6/7/2023
Page 17 of 101
Multiple Statements per Line

Use commas or semicolons to enter more than one statement at once.


Commas allow multiple statements per line without suppressing output.

>> a = 5 ; b = sin(a), c = cosh(a)


b =
-0.9589

c =
74.2099

6/7/2023
Page 18 of 101
M ATLAB Variables Names
Legal variable names:
• Begin with one of a–z or A–Z
• Have remaining characters chosen from a–z, A–Z, 0–9, or
• Have a maximum length of 31 characters
• Should not be the name of a built-in variable, built-in function, or
user-defined function

Examples: Note: mySum and mysum are different


xxxxxxxxx variables. M ATLAB is case
pipeRadius sensitive.
widgets_per_box
mySum
mysum

6/7/2023
Page 19 of 101
Built-in M ATLAB Variables (1)

Name Meaning
ans value of an expression when that expression is not assigned to
a variable
eps floating point precision
pi π, (3.141492 . . . )
realmax largest positive floating point number
realmin smallest positive floating point number
Inf ∞, a number larger than realmax,
the result of evaluating 1/0.

NaN not a number, the result of evaluating 0 / 0

6/7/2023
Page 20 of 101
Built-in M ATLAB Variables (2)

Rule: Only use built-in variables on the right-hand side of an expression.


Reassigning the value of a built-in variable can create problems
with built-in functions.

Exception: i and j are preassigned to −1 One or both of i or j are


often reassigned as loop indices. More on this later.

6/7/2023
Page 21 of 101
Matrices and Vectors

All M ATLAB variables are matrices


• A vector is a matrix with one row or one column.
• A scalar is a matrix with one row and one column.
• A character string is a row of column vector of characters.

Consequences:
• Rules of linear algebra apply to addition, subtraction and multiplication.
• Elements in the vectors and matrices are addressed with Fortran-like
subscript notation, e.g.,, x (2 ), A(4,5). Usually, this notation is clear
from context, but it can be confused with a function call,

y = sqrt(5) s q r t is a built-in function


z = f(3) Is f a function or variable?

6/7/2023
Page 22 of 101
Creating M ATLAB Variables

M ATLAB variables are created with an assignment statement


>> x = expression

where expressionis a legal combinations of numerical values,


mathematical operators, variables, and function calls.
The expression can involve:
• Manual entry
• Built-in functions that return matrices
• Custom (user-written) functions that return matrices
• Loading matrices from text files or “mat” files

6/7/2023
Page 23 of 101
Element-by-Element Creation of Matrices and Vectors (1)
A matrix, a column vector, As M ATLAB variables:
and a row vector: >> A = [ 3 2 ; 3 1 ; 1 4 ]
A =
3 2 3 2
A= 3 1 3 1
1 4
1 4
>> x = [ 5 ; 7 ; 9 ; 2 ]
x =
5 5
7 7
x=
9 9
2 2
>> v = [ 9 -3 4 1 ]
v =
v= 9 −3 4 1 9 -3 4 1

6/7/2023
Page 24 of 101
Element-by-Element Creation of Matrices and Vectors (2)
For manual entry, the elements in a vector are enclosed in square brackets. When
creating a row vector, separate elements with a space.

>> v = [ 7 3 9]
v =
7 3 9

Separate columns with a semicolon

>> w = [ 2 ; 6 ; 1]
w=
2
6
1

6/7/2023
Page 25 of 101
Element-by-Element Creation of Matrices and Vectors (3)

When assigning elements to matrix, row elements are separated by spaces,


and columns are separated by semicolons
>> A = [1 2 3 ; 5 7 11; 13 17 19]
A =
1 2 3
5 7 11
13 17 19

6/7/2023
Page 26 of 101
Transpose Operator (1)

Once it is created, a variable can be transformed with other operators.


The transpose operator converts a row vector to a column vector (and vice versa),
and it changes the rows of a matrix to columns.

>> v = [ 2 4 1 7 ]
v =
2 4 1 7

>> w = v ’
w=
2
4
1
7

6/7/2023
Page 27 of 101
Transpose Operator (2)

>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
A =
1 2 3
4 5 6
7 8 9

>> B = A’
B =
1 4 7
2 5 8
3 6 9

6/7/2023
Page 28 of 101
Overwriting Variables

Once a variable has been created, it can be reassigned


>> x = 2 ;
>> x = x + 2
x =
4

>> y = [ 1 2 3 4 ]
y =
1 2 3 4

>> y = y ’
y =
1
2
3
4

6/7/2023
Page 29 of 101
Using Functions to Create Matrices and Vectors

Create vectors with built-in functions:

l i n s p a c e and logspace

Create matrices with built-in functions:

ones, zeros, eye, diag, . . .

Note that ones and zeros can also be used to create vectors.

6/7/2023
Page 30 of 101
Creating vectors with l i n s p a c e (1)

The l i n s p a c e function creates vectors with elements having uniformlinear spacing.


Syntax:
x = linspace(startValue,endValue)
x = linspace(startValue,endValue,nelements)
creates nelements elements between startValue and endValue. The default
value for nelements is 100

Examples:
>> u = l i n s p a c e ( 0 . 0 , 0 . 2 5 , 5 )
u =
0 0.0625 0.1250 0.1875 0.2500

>> u = l i n s p a c e ( 0 . 0 , 0 . 2 5 ) ;

Remember: Ending a statement with semicolon suppresses the output.

6/7/2023
Page 31 of 101
Creating vectors with l i n s p a c e (2)

Column vectors are created by appending the transpose operator to


linspace
>> v = l i n s p a c e ( 0 , 9 , 4 ) ’
v =
0
3
6
9

6/7/2023
Page 32 of 101
Example: A Table of Trig Functions
>> x = l i n s p a c e ( 0 , 2 * p i , 6 ) ’ ; (note transpose)
>> y = s i n ( x ) ;
>> z = c o s ( x ) ;
>> [ x y z ]
ans =
0 0 1.0000
1.2566 0.9511 0.3090
2.5133 0.5878 -0.8090
3.7699 -0.5878 -0.8090
5.0265 -0.9511 0.3090
6.2832 0 1.0000

The expressions y = s i n ( x ) and z = c o s ( x ) take advantage of


vectorization. If the input to a vectorized function is a vector or matrix, the
output is often a vector or matrix having the same shape. More on this later.

6/7/2023
Page 33 of 101
Creating vectors with logspace

The logspace function creates vectors with elements having uniform


logarithmic spacing.
Syntax:

x = logspace(startValue,endValue)
x = logspace(startValue,endValue,nelements)

creates nelements elements between 10 startValue and 10 endValue . The default


value of nelements is 100.
Example:
>> w = l o g s p a c e ( 1 , 4 , 4 )
w=
10 100 1000 10000

6/7/2023
Page 34 of 101
Functions to Create Matrices (1)

Name Operation(s) Performed


diag create a matrix with a specified diagonal entries, or extract
diagonal entries of a matrix

eye create an identity matrix


ones create a matrix filled with ones
rand create a matrix filled with random numbers
zeros create a matrix filled with zeros
linspace create a row vector of linearly spaced
elements
logspace create a row vector of logarithmically spaced elements

6/7/2023
Page 35 of 101
Functions to Create Matrices (2)
Use ones and zeros to set intial values of a matrix or vector.
Syntax:
A = ones(nrows,ncols)
A = zeros(nrows,ncols)

Examples:
>> D = ones(3,3)
D =
1 1 1
1 1 1
1 1 1
>> E = ones(2,4)
E =
1 1 1 1
1 1 1 1

6/7/2023
Page 36 of 101
Functions to Create Matrices (3)
ones and zeros are also used to create vectors. To do so, set either
nrows or ncols to 1.
>> s = o n e s ( 1 ,4 )
s =
1 1 1 1

>> t = z e r o s ( 3 , 1 )
t =
0
0
0

6/7/2023
Page 37 of 101
Functions to Create Matrices (4)
The eye function creates identity matrices of a specified size. It can also
create non-square matrices with ones on the main diagonal.
Syntax:
A = eye(n)
A = eye(nrows,ncols)

Examples:
>> C = eye(5)
C =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

6/7/2023
Page 38 of 101
Functions to Create Matrices (5)
The optional second input argument to eye allows non-square matrices to
be created.
>> D = e ye (3,5)
D =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0

where D i , j = 1 whenever i = j.

6/7/2023
Page 39 of 101
Functions to Create Matrices (6)

The diag function can either create a matrix with specified diagonal
elements, or extract the diagonal elements from a matrix
Syntax:
A = diag(v)
v = diag(A)

Example: Use dia g to create a matrix


>> v = [ 1 2 3 ] ;
>> A = d i a g ( v )
A =
1 0 0
0 2 0
0 0 3

6/7/2023
Page 40 of 101
Functions to Create Matrices (7)
Example: Use diag to extract the diagonal of a matrix
>> B = [ 1 : 4 ; 5 : 8 ; 9 : 1 2 ]
B =
1 2 3 4
5 6 7 8
9 10 11 12

>> w = d i a g ( B )
w=
1
6
11

6/7/2023
Page 41 of 101
Functions to Create Matrices (8)

The action of the dia g function depends on the characteristics and


number of the input(s). This polymorphic behavior of M ATLAB functions
is common. Refer to the on-line documentation for the possible variations.
>> A = d i a g ( [ 3 2 1 ] ) Create a matrix with a specified diagonal
A =
3 0 0
0 2 0
0 0 1

>> B = [ 4 2 2 ; 3 6 9 ; 1 1 7 ] ;
>> v = d i a g ( B ) Extract the diagonal of a matrix
v =
4
6
7

6/7/2023
Page 42 of 101
Subscript Notation (1)

If A is a matrix, A ( i , j ) selects the element in the ith row and jth column.
Subscript notation can be used on the right-hand side of an expression to
refer to a matrix element.
>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] ;
>> b = A ( 3 , 2 )
b =
8

>> c = A ( 1 , 1 )
c =
1

6/7/2023
Page 43 of 101
Subscript Notation (1)

Subscript notation is also used to assign matrix elements


>> A ( 1 , 1 ) = c/b
A =
0.2500 2.0000 3.0000
4.0000 5.0000 6.0000
7.0000 8.0000 9.0000

Referring to elements beyond the dimensions the matrix results in an error


>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] ;
>> A ( 1 , 4 )
??? Index exceeds matrix dimensions.

6/7/2023
Page 44 of 101
Subscript Notation (1)

Assigning an element that is beyond the existing dimensions of the matrix


causes the matrix to be resized!
>> A = [1 2 3 ; 4 5 6 ; 7 8 9 ] ;
A =
1 2 3
4 5 6
7 8 9

>> A ( 4 , 4 ) = 11
A =
1 2 3 0
4 5 6 0
7 8 9 0
0 0 0 11

In other words, M ATLAB automatically resizes matrices on the fly.

6/7/2023
Page 45 of 101
Colon Notation (1)

Colon notation is very powerful and very important in the effective use of
M ATLAB . The colon is used as both an operator and as a wildcard.

Use colon notation to:


• create vectors
• refer to or extract ranges of matrix elements

6/7/2023
Page 46 of 101
Colon Notation (2)

Syntax:
startValue : endValue
startValue : increment : endValue

Note: startValue, increment, and endValue do not need to be integers

6/7/2023
Page 47 of 101
Colon Notation (3)

Creating row vectors:


>> s = 1:4
s =
1 2 3 4

>> t = 0 : 0 . 1 : 0 . 4
t =
0 0.1000 0.2000 0.3000 0.4000

6/7/2023
Page 48 of 101
Colon Notation (4)

Creating column vectors:


>> u = ( 1 : 5 ) ’
u =
1
2
3
4
5

>> v = 1 : 5 ’
v =
1 2 3 4 5

v is a row vector because 1 : 5 ’ creates a vector between 1 and the


transpose of 5.

6/7/2023
Page 49 of 101
Colon Notation (5)

Use colon as a wildcard to refer to an entire column or row


>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ] ;
>> A ( : , 1 )
ans =
1
4
7

>> A ( 2 , : )
ans =
4 5 6

6/7/2023
Page 50 of 101
Colon Notation (6)

Or use colon notation to refer to subsets of columns or rows


>> A ( 2 : 3 , 1 )
ans =
4
7

>> A ( 1 : 2 , 2 : 3 )
ans =
ans =
2 3
5 6

6/7/2023
Page 51 of 101
Colon Notation (7)

Colon notation is often used in compact expressions to obtain results that


would otherwise require several steps.
Example:
>> A = o n e s ( 8 , 8 ) ;
>> A ( 3 : 6 , 3 : 6 ) = z e r o s ( 4 , 4 )
A =
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 0 0 0 0 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1

6/7/2023
Page 52 of 101
Colon Notation (8)

Finally, colon notation is used to convert any vector or matrix to a column vector.
Example:
>> x = 1 : 4 ;
>> y = x ( : )
y =
1
2
3
4

6/7/2023 Page 53 of 101


Colon Notation (9)

Colon notation converts a matrix to a column vector by appending the


columns of the input matrix
>> A = r a n d ( 2 , 3 ) ;
>> v = A ( : )
v =
0.9501
0.2311
0.6068
0.4860
0.8913
0.7621
0.4565

Note: The rand function generates random elements between zero and one.
Repeating the preceding statements will, in all likelihood, produce different
numerical values for the elements of v.

6/7/2023
Page 54 of 101
Additional Types of Variables

Matrix elements can either be numeric values or characters. Numeric


elements can either be real or complex (imaginary).
More general variable types are available: n-dimensional arrays (where
n > 2), structs, cell arrays, and objects. Numeric (real and complex) and
string arrays of dimension two or less will be sufficient for our purposes.

Consider some simple variations on numeric and string matrices:


• Complex Numbers
• Strings
• Polynomials

6/7/2023
Page 55 of 101
Complex Numbers
M ATLAB automatically performs complex arithmetic
>> s q r t ( - 4 )
ans =
0 + 2.0000i

>> x = 1 + 2 * i (or, x = 1 + 2*j)


x =
1.0000 + 2.0000i

>> y = 1 - 2 * i
y =
1.0000 - 2.0000i

>> z = x*y
z =
5

6/7/2023
Page 56 of 101
Unit Imaginary Numbers (1)

i and j are ordinary M ATLAB variables preassigned with the value −1


>> i ^ 2
ans =
-1

Both or either i and j can be reassigned


>> i = 5 ;
>> t = 8 ;
>> u = s q r t ( i - t ) ( i - t = - 3 , not - 8 + i )
u
=
>> u*u 0 + 1.7321i
ans =
-3.0000

6/7/2023 Page 57 of 101


Unit Imaginary Numbers (2)

The i and j variables are often used for array subscripting. Set i (or j ) to
an integer value that is also a valid array subscript.
>> A = [1 2 ; 3 4 ] ;
>> i = 2 ;
>> A ( i , i ) = 1
A =
1 2
3 1

>> x = A ( 2 , j )
??? S u b s c r i p t i n d i c e s must e i t h e r be r e a l p o s i t i v e i n t e g e r s or l o g i c a l s .

Note: When working with complex numbers, it is a good idea to


reserve either i or j for the unit imaginary value −1.

6/7/2023
Page 58 of 101
Euler Notation (1)

Euler notation represents a complex number by a phaser

imaginary
z = ζe iθ
x = Re(z) = |z| cos(θ) = ζ cos(θ) iy z =  ei

y = iIm(z) = i|z| sin(θ) = iζ sin(θ)

x real

6/7/2023
Page 59 of 101
Functions for Complex Arithmetic (1)

Function Operation
abs Compute the magnitude of a number
a b s ( z ) is equivalent to s q r t ( r e a l ( z ) ^ 2 + imag(z)^2 )
angle Angle of complex number in Euler notation
exp If x is real, exp(x) = e x
If z is complex, exp(z) = eRe(z)(cos(Im(z) + i sin(Im(z))
conj Complex conjugate of a number
imag Extract the imaginary part of a complex number
real Extract the real part of a complex number

6/7/2023 Page 60 of 101


Functions for Complex Arithmetic (2)

Examples:
>> z e t a = 5 ; theta = p i / 3 ; >> x = r e a l ( z )
>> z = z e t a * e x p ( i * t h e t a ) x =
z = 2.5000
2.5000 + 4.3301i
>> y = imag(z)
>> a b s ( z ) y =
ans = 4.3301
5
>> a n g l e (z)*1 80 /pi
>> s q r t ( z * c o n j ( z ) ) ans =
ans = 60.0000
5

Remember: There is no “degrees” mode in M ATLAB . All angles are in radians.

6/7/2023 Page 61 of 101


Strings

• Strings are matrices with Examples:


character elements. >> f i r s t = ’ J o h n ’ ;
>> l a s t = ’ C o l t r a n e ’ ;
• String constants are enclosed in >> name = [ f i r s t , ’ ’ , l a s t ]
single quotes name =
John Coltrane
• Colon notation and subscript
operations apply >> length(name)
ans =
13

>> name(9:13)
ans =
trane

6/7/2023 Page 62 of 101


Functions for String Manipulation (1)

Function Operation
char Converts an integer to the character using ASCII codes, or
combines characters into a character matrix
findstr Finds one string in another string
length Returns the number of characters in a string
num2str Converts a number to string
str2num Converts a string to a number
strcmp Compares two strings
strmatch Identifies rows of a character array that begin with a string
strncmp Compares the first n elements of two strings
sprintf Converts strings and numeric values to a string

6/7/2023 Page 63 of 101


Functions for String Manipulation (2)

num2str converts a number to a string


>> msg1 = [ ’ T h e r e are ’ , n u m 2 s t r ( 1 0 0 / 2 . 5 4 ) , ’ inches i n a meter’]
msg1 =
There are 39.3701 inches i n a meter

For greater control over format of the number-to-string conversion, use


sprintf
>> msg2 = s p r i n t f ( ’ T h e r e are %5.2f c u b i c inches i n a l i t e r ’ , 1 0 0 0 / 2 . 5 4 ^ 3 )
msg2 =
There are 61.02 c u b i c inches i n a l i t e r

The M ATLAB s p r i n t f function is similar to the C function of the same


name, but it uses single quotes for the format string.

6/7/2023 Page 64 of 101


Functions for String Manipulation (3)

The char function can be used to combine strings


>> both = char(msg1,msg2)
both =
There are 39.3701 inches i n a meter
There are 61.02 c u b i c inches i n a l i t e r

or to refer to individual characters by their ASCII codes1


>> c h a r ( 4 9)
ans =
1
>> c h a r ( [ 7 7 65 84 76 65 6 6 ] )
ans =
MATLAB
1See e.g.,, www.asciicodes.com or w i k i p e d i a . o r g / w i k i / A S C I I .

6/7/2023 Page 65 of 101


Functions for String Manipulation (4)

Use strcmp to test whether two strings are equal, i.e., if they contain the
same sequence of characters.
>> msg1 = [ ’ T h e r e are ’ , n u m 2 s t r ( 1 0 0 / 2 . 5 4 ) , ’ inches i n a m e t e r ’ ] ;
>> msg2 = s p r i n t f ( ’ T h e r e are %5.2f c u b i c inches i n a l i t e r ’ , 1 0 0 0 / 2 . 5 4 ^ 3 ) ;
>> strcmp(msg1,msg2)
ans =
0

Compare the first n characters of two strings with strncmp


>> strncmp(msg1,msg2,9)
ans =
1

The first nine characters of both strings are “There are”, so


strncmp(msg1,msg2,9) returns 1, or true.

6/7/2023 Page 66 of 101


Functions for String Manipulation (5)

Locate occurances of one string in another string with f i n d s t r


>> f i n d s t r ( ’ i n ’ , m s g 1 )
ans =
19 26

>> msg1(19:20)
ans =
in

Page 67 of 101
6/7/2023
Polynomials
M ATLAB polynomials are stored as vectors of coefficients. The polynomial
coefficients are stored in decreasing powers of x

P n (x) = c 1 x n + c 2 x n−1 + . . . + c n x + c n + 1

Example: Evaluate x 3 − 2x + 12 at x = −1.5


Store the coefficients of the polynomial in vector c:
>> c = [ 1 0 -2 12];

Use the built-in p o l y v a l function to evaluate the polynomial.


>> p o l y v a l ( c , 1 . 5 )
ans =
12.3750

6/7/2023 Page 68 of 101


Functions for Manipulating Polynomials

Function Operations performed


conv Product (convolution) of two polynomials
deconv Division (deconvolution) of two polynomials
poly Create a polynomial having specified roots
polyder Differentiate a polynomial
polyval Evaluate a polynomial
polyfit Polynomial curve fit
roots Find roots of a polynomial

6/7/2023 Page 69 of 101


A Quick Overview of Linear Algebra in M ATLAB
The name “M ATLAB ” is a shortened form of “MATrix LABoratory”.
M ATLAB data types and syntax make it easy to perform standard
operations of linear algebra including addition, subtraction, and
multiplication of vectors and matrices.
Chapter 7 provides a detailed review of linear algebra. Here we provide a
simple introduction to some operations that are necessary for routine
calculation.
• Vector addition and subtraction
• Inner and outer products
• Vectorization
• Array operators

6/7/2023 Page 70 of 101


Vector Addition and Subtraction

Vector and addition and subtraction are element-by-element operations.


Example:
>> u = [10 9 8 ] ; ( u and v are row vectors)
>> v = [ 1 2 3 ] ;
>> u+v
ans =
11 11 11

>> u-v
ans =
9 7 5

6/7/2023 Page 71 of 101


Vector Inner and Outer Products

The inner product combines two vectors to form a scalar

𝜎 = 𝑢. 𝑣 = 𝑢𝑣 𝑇 ↔ 𝜎 = ෍ 𝑢𝑖 𝑣𝑖

The outer product combines two vectors to form a matrix

A = u T v ⇐⇒ a i , j = u i v j

Page 72 of 101
6/7/2023
Inner and Outer Products in M ATLAB

Inner and outer products are supported in M ATLAB as natural extensions


of the multiplication operator
>> u = [10 9 8 ] ; (u and v are row vectors)
>> v = [ 1 2 3 ] ;
>> u*v’ (inner product)
ans =
52

>> u’*v (outer product)


ans =
10 20 30
9 18 27
8 16 24

Page 73 of 101
6/7/2023
Vectorization

• Vectorization is the use of single, compact expressions that operate on all


elements of a vector without explicitly writing the code for a loop. The
loop is executed by the M ATLAB kernel, which is much more efficient at
evaluating a loop in interpreted M ATLAB code.
• Vectorization allows calculations to be expressed succintly so that
programmers get a high level (as opposed to detailed) view of the
operations being performed.
• Vectorization is important to make M ATLAB operate efficiently2.

2Recent versions of M ATLAB have improved the efficiency for some non-vectorized code.

6/7/2023 Page 74 of 101


Vectorization of Built-in Functions

Most built-in function support vectorized operations. If the input is a scalar the
result is a scalar. If the input is a vector or matrix, the output is a vector or
matrix with the same number of rows and columns as the input.
Example:
>> x = 0 : p i / 4 : p i (define a row vector)
x =
0 0.7854 1.5708 2.3562 3.1416

>> y = c o s ( x ) (evaluate cosine of each x ( i ) )


y =
1.0000 0.7071 0 -0.7071 -1.0000

6/7/2023 Page 75 of 101


Vectorized Calculations

More examples
>> A = p i * [ 1 2 ; 3 4 ] >> B = A/2
A = B =
3.1416 6.2832 1.5708 3.1416
9.4248 12.5664 4.7124 6.2832

>> S = s i n ( A ) >> T = s i n ( B )
S = T =
0 0 1 0
0 0 -1 0

Page 76 of 101
6/7/2023
Array Operators

Array operators support element-by-element operations that are not


defined by the rules of linear algebra.
Array operators have a period prepended to a standard operator.

Symbol Operation
.* element-by-element multiplication

./ element-by-element “right” division

.\ element-by-element “left” division

.^ element-by-element exponentiation

Array operators are a very important tool for writing vectorized code.

6/7/2023 Page 77 of 101


Using Array Operators (1)

Examples: Element-by-element multiplication and division


>> u = [ 1 2 3 ] ;
>> v = [ 4 5 6 ] ;

Use . * and . / for element-by-element multiplication and division


>> w = u.*v
w=
4 10 18

>> x = u . / v
x =
0.2500 0.4000 0.5000

6/7/2023 Page 78 of 101


Using Array Operators (1)

Examples: Element-by-element multiplication and division


>> u = [1 2 3 ] ;
>> v = [4 5 6 ] ;
>> y = s i n ( p i * u / 2 ) . * c o s ( p i * v / 2 )
y =
1 0 1

>> z = s i n ( p i * u / 2 ) . / c o s ( p i * v / 2 )

Warning: D i v i d e by z e r o .
z =
1 NaN 1

Page 79 of 101
6/7/2023
Using Array Operators (2)

Examples: Application to matrices


>> A = [1 2 3 4; 5 6 7 8];
>> B = [8 7 6 5; 4 3 2 1];
>> A.*B
ans =
8 14 18 20
20 18 14 8

>> A*B
??? E r r o r using ==> *
Inner matrix dimensions must agree

The last statement causes an error because the number of columns in A is


not equal to the number of rows in B — a requirement for A and B to be

6/7/2023 Page 80 of 101


Using Array Operators (3)

>> A = [ 1 2 3 4 ; 5 6 7 8 ] ;
>> B = [ 8 7 6 5 ; 4 3 2 1 ] ;
>> A*B’
ans =
60 20
164 60

The number of columns in A is equal to the number of rows in B T , so A*B’


is a legal matrix-matrix multiplication.
Array operators also apply to matrix powers.
>> A.^2
ans =
1 4 9 16
25 36 49 64

6/7/2023 Page 81 of 101


The M ATLAB Workspace (1)

All variables defined as the result of entering statements in the command


window, exist in the M ATLAB workspace.
At the beginning of a M ATLAB session, the workspace is empty.
Being aware of the workspace allows you to

• Create, assign, and delete variables


• Load data from external files
• Manipulate the M ATLAB path

6/7/2023 Page 82 of 101


The M ATLAB Workspace (2)

The c l e a r command deletes variables from the workspace. The who


command lists the names of variables in the workspace
>> c l e a r (Delete all variables from the workspace)
>> who
(No response, no variables are defined after ‘clear’)

>> a = 5; b = 2; c = 1;
>> d ( 1 ) = sqrt(b^2 - 4*a*c);
>> d(2) = -d ( 1 ) ;
>> who

Your v a r i a b l e s a r e :

a b c d

Page 83 of 101
6/7/2023
The M ATLAB Workspace (3)

The whos command lists the name, size, memory allocation, and the class
of each variables defined in the workspace.
>> whos

Name Size Bytes Class

a 1x1 8 double a rra y


b 1x1 8 double array
c 1x1 8 double a rra y
d 1x2 32 double a rra y (complex)

Grand t o t a l i s 5 elements u s i n g 56 bytes

6/7/2023 Page 84 of 101


The M ATLAB Workspace (4)

The whos command returns the array dimensions, memory requirement


and class for each variable in the workspace.
Built-in variable classes are double, char, sparse, s t r u ct , and c e l l .
The class of a variable determines the type of data that can be stored in it.
We will be dealing primarily with numeric data, which is the double class,
and occasionally with string data, which is in the char class.

Page 85 of 101
6/7/2023
Working with External Data Files

Write data to a file


save fileName
save fileName variable1 variable2 . . .
save fileName variable1 variable2 . . . - a s c i i

Read in data stored in matrices


load fileName
load fileName matrixVariable

6/7/2023 Page 86 of 101


Loading Data from External File

Example: Load data from a file and plot the data


>> load wolfSun.dat;
>> xdata = w o l f S u n ( : , 1 ) ;
>> ydata = w o l f S u n ( : , 2 ) ;
>> plot(xdata,ydata)

6/7/2023 Page 87 of 101


The M ATLAB Path

M ATLAB will only use those functions and data files that are in its path.
To add N:\IMAUSER\ME352\PS2 to the path, type

>> p = path;
>> path(p,’N:\IMAUSER\ME352\PS2’);

M ATLAB version 5 and later has an interactive path editor that makes it
easy to adjust the path.
The path specification string depends on the operating system. On a
Unix/Linux computer a path setting operation might look like:
>> p = path;
>> path(p,’~/matlab/ME352/ps2’);

Page 88 of 101
6/7/2023
Plotting

• Plotting (x, y) data

• Axis scaling and annotation

• 2D (contour) and 3D (surface) plotting

6/7/2023 Page 89 of 101


Plotting (x, y) Data (1)

Two dimensional plots are created with the p l o t function


Syntax:
plot(x,y)
plot(xdata,ydata,symbol)
p l o t ( x 1 ,y 1 ,x 2 ,y 2 ,. ..)
plot(x1,y1,symbol1,x2,y2,symbol2,...)

Note: x and y must have the same shape, x1 and y1 must have the
same shape, x2 and y2 must have the same shape, etc.

Page 90 of 101
6/7/2023
Plotting (x, y) Data (2)

1
Example: A simple line plot 0.8

>> x = l i n s p a c e ( 0 , 2 * p i ) ; 0.6

>> y = s i n ( x ) ; 0.4

>> p l o t ( x , y ) ; 0.2

−0.2

−0.4

−0.6

−0.8

−1
0 1 2 3 4 5 6 7

Page 91 of 101
6/7/2023
Line and Symbol Types (1)

The curves for a data set are drawn from combinations of the color,
symbol, and line types in the following table.
Color Symbols Line
y yellow . point ^ triangle (up) - solid
m magenta o circle < triangle (left) : dotted
c cyan x x-mark > triangle (right) -. dashdot
r red + plus p pentagram -- dashed
g green * star h hexagram
b blue s square
w white d diamond
k black v triangle
(down)

To choose a color/symbol/line style, chose one entry from each


column.

6/7/2023 Page 92 of 101


Line and Symbol Types (2)

Examples:
Put yellow circles at the data points:
plot(x,y,’yo’)

Plot a red dashed line with no symbols:


p l o t ( x , y , ’ r - -’)

Put black diamonds at each data point and connect the diamonds with black das
p l o t ( x , y , ’ k d - - ’)

Page 93 of 101
6/7/2023
Alternative Axis Scaling (1)

Combinations of linear and logarithmic scaling are obtained with functions


that, other than their name, have the same syntax as the p l o t function.
Name Axis scaling
loglog log 10 (y) versus log 10 (x)
plot linear y versus x
semilogx linear y versus log 10 (x)
semilogy log 10 (y) versus linear x

Note: As expected, use of logarithmic axis scaling for data sets with
negative or zero values results in a error. M ATLAB will complain
and then plot only the positive (nonzero) data.

6/7/2023 Page 94 of 101


Alternative Axis Scaling (2)

10
Example:
8
>> x = l i n s p a c e ( 0 , 3 ) ;
6
>> y = 1 0 * e x p ( -2*x);
>> p l o t ( x , y ) ; 4

2
0
0 1 2 3
1
10
>> s e m i l o g y ( x , y ) ;
0
10

-1
10

-2
10
0 1 2 3

6/7/2023 Page 95 of 101


Multiple plots per figure window (1)

The subplot function is used to create a matrix of plots in a single figure


window.
Syntax:
subplot(nrows,ncols,thisPlot)

Repeat the values of nrows and ncols for all plots in a single figure
window. Increment thisPlot for each plot

Page 96 of 101
6/7/2023
Multiple plots per figure window (1)

Example:
>> x = l i n s p a c e ( 0 , 2 * p i ) ;
>> s u b p l o t ( 2 , 2 , 1 ) ;
>> p l o t ( x , s i n ( x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(x)’);

>> s u b p l o t ( 2 , 2 , 2 ) ;
>> p l o t ( x , s i n ( 2 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(2x)’);

>> s u b p l o t ( 2 , 2 , 3 ) ;
>> p l o t ( x , s i n ( 3 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(3x)’);

>> s u b p l o t ( 2 , 2 , 4 ) ;
>> p l o t ( x , s i n ( 4 * x ) ) ; axis([0 2*pi - 1 . 5 1 . 5 ] ) ; title(’sin(4x)’);

(See next slide for the plot.)

Page 97 of 101
6/7/2023
Multiple plots per figure window (2)

sin(x) sin(2x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6

sin(3x) sin(4x)
1.5 1.5
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
-1.5 -1.5
0 2 4 6 0 2 4 6

6/7/2023 Page 98 of 101


Plot Annotation

Name Operation(s) performed


axis Reset axis limits
grid Draw grid lines at the major ticks marks on the x and y axes
gtext Add text to a location determined by a mouse click
legend Create a legend to identify symbols and line types when multiple
curves are drawn on the same plot
text Add text to a specified ( x , y ) location
xlabel Label the x-axis
ylabel Label the y-axis
title Add a title above the plot

Page 99 of 101
6/7/2023
Plot Annotation Example (1)

>> D = load(’pdxTemp.dat’); m = D(:,1); T = D(:,2:4);

>> p l o t ( m , t ( : , 1 ) , ’ r o ’ , m , T ( : , 2 ) , ’ k + ’ , m , T ( : , 3 ) , ’ b - ’);
>> xlabel(’Month’);
>> ylabel(’Temperature ( { } ^ \ c i r c F ) ’ ) ;
>> t i t l e ( ’ M o n t h l y average temperature a t P D X ’ ) ;
>> a x i s ( [ 1 12 20 1 0 0 ] ) ;
>> legend(’High’,’Low’,’Average’,2);

Note: The pdxTemp.dat file is in the data directory of the NMM


toolbox. Make sure the toolbox is installed and is included in the
M ATLAB path.

(See next slide for the plot.)

6/7/2023 Page 100 of 101


Plot Annotation Example (2)

Monthly average temperature for Portland International Airport


100
High
Low
90 Average

80
Temperature (degrees F)

70

60

50

40

30

20
2 4 6 8 10 12
Month

6/7/2023 Page 101 of 101


Assignment
Instructions:

Complete the MATLAB Onramp course using mathworks account


opened using your institutional email ([email protected]).
Then submit both the PDF and link of your course completion certificate
in the assignment opened in teams before the due date.

Course Link:

https://matlabacademy.mathworks.com/details/matlab-onramp/gettingstarted

6/7/2023 Page 102 of 102

You might also like