0% found this document useful (0 votes)
12 views450 pages

CPA All Chapters

Uploaded by

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

CPA All Chapters

Uploaded by

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

INTRODUCTION TO MATLAB

NED University of Engineering & Technology


Outline
• Different windows in MATLAB

• Arithmetic operations with scalars using MATLAB.

• Scalar variables and their use in arithmetic


calculations

• Elementary Math built-in functions

• Script files  how to write, save, and execute


simple MATLAB programs

Textbook: A. Gilat, Matlab: An Introduction with Applications 4th Edition. John Wiley
& Sons, Incorporated, 2017. (Chapter 1: Introduction)
INTRODUCTION TO MATLAB 3 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Different windows in MATLAB


INTRODUCTION TO MATLAB 4 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Prerequisites for solving a problem using MATLAB

• Mathematics

• An algorithm

• The exact rules for writing MATLAB statements

• Correct usage of MATLAB utilities

• Converting algorithm into MATLAB statements


and/or program
INTRODUCTION TO MATLAB 5 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Default view of MATLAB desktop

CURRENT WORKSPACE
FOLDER WINDOW
WINDOW
COMMAND WINDOW

COMMAND HISTORY
WINDOW
INTRODUCTION TO MATLAB 6 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Default view: Home  Layout  Default


INTRODUCTION TO MATLAB 7 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Executing commands one at a time


• Main window: For executing commands
Command 1: A=5
press enter
To execute
• Command line: The line with command prompt >>
Command 2: B=10 each
press enter
command:
Command 3: C=A+B
Press Enter
press enter

The cursor next to the command


prompt is prompting the user to enter
the next Command
INTRODUCTION TO MATLAB 8 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Executing several commands

3 commands in the same


line separated by a
comma
Order of
execution:
Left to Right
INTRODUCTION TO MATLAB 9 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Editing

• Editing:

The already executed command can not be corrected


and re-executed
INTRODUCTION TO MATLAB 10 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Editing

Command-line editing:

• Left-arrow, Right-arrow

• Up-arrow and Down-arrow for accessing history

• Smart recall: type some character and press


Up-arrow and Down-arrow
INTRODUCTION TO MATLAB 11 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Use of percent symbol (%)

Comment
Comment line is not executed when ENTER is
pressed

Comments are added to aid the programmer for his/her reference


INTRODUCTION TO MATLAB 12 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Use of Semi-colon (;)

Output of the command is displayed

Output of the command


is not displayed
INTRODUCTION TO MATLAB 13 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Use of Semi-colon (;)


INTRODUCTION TO MATLAB 14 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Use of the command clc

clc  clears the command window only

CAUTION: The commands are CASE-SENSITIVE!


INTRODUCTION TO MATLAB 15 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Drawbacks of a command window

• The commands in the Command window


cannot be saved and executed again.

• It is not interactive.

• Already executed command can not be


modified

• Better option: script file


INTRODUCTION TO MATLAB 16 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command Window: Font size: Home  Preferences  Fonts


INTRODUCTION TO MATLAB 17 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Useful commands you should know


CAUTION: The commands are CASE-SENSITIVE!

• help  lists all the primary help topics.

• help <command>  displays information about the command.

• doc On-line help  accesses the hypertext reference manual.

• doc <command>  displays information about the command.

• type <command>  Displays the actual MATLAB code for this


command.

• lookfor <keyword>  Searches all MATLAB commands for this


keyword.
INTRODUCTION TO MATLAB 18 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Useful commands you should know

ATTENTION: The commands are CASE-SENSITIVE!

• who  Lists all the current variables.

• whos  Lists all the current variables in more detail than who.

• save  Saves all of your variables.

• ^C  Abort the command which is currently executing (i.e., hold down


the control key and type c).
INTRODUCTION TO MATLAB 19 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Useful commands you should know

ATTENTION: The commands are CASE-SENSITIVE!

• clc  clears the command window (but does not clear the saved
variables in the workspace)

• clear all  deletes all the saved variables from the workspace (but
does not clear the command window) and brings the cursor at top

• clear variable  deletes only that particular variable from the


workspace

• date  gives current date

• calendar shows up the calendar of the ongoing month


INTRODUCTION TO MATLAB 20 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Busy…
INTRODUCTION TO MATLAB 21 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Command History

• The Command History Window  includes commands from previous


sessions.

• A command in the Command History Window can be used again in the


Command Window.

• By double-clicking on the command, the command is reentered in the


Command Window and executed.

• It is also possible to drag the command to the Command Window, make


changes if needed, and then execute it.

• Clearing Command history:


• Whole history
• A selection
INTRODUCTION TO MATLAB 22 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Simple Arithmetic Operations With Scalars

Addition: 3+2
Subtraction: 3-2
Multiplication: 3*2
Division: 3/2 or 2\3
Exponent: 3^2
INTRODUCTION TO MATLAB 23 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Order of Precedence
INTRODUCTION TO MATLAB 24 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Order of Precedence: Practice


INTRODUCTION TO MATLAB 25 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Display formats
Command Description Example
>> 290/7
format short
upto 4 decimal digits ans =
(default)
41.4286
>> 290/7
ans =
format long upto 15 decimal digits
41.4285714285
71431
>> 290/7
format short e scientific notation with 4 decimal digits ans =
4.1429e+001
>> 290/7
ans =
format long e scientific notation with 15 decimal digits
4.14285714285
7143e+001
INTRODUCTION TO MATLAB 26 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Display formats
Command Description Example
>> 290/7
format short g 5 s.g.f of floating digits ans =
41.429
>> 290/7
ans =
format long g 15 s.g.f of floating digits
41.4285714285
714
>> 290/7
format bank upto 2 decimal digits ans =
41.43
Eliminates empty lines to allow more lines with information
format compact
displayed on the screen.
format loose
Adds empty lines (opposite of compact).
(default)
INTRODUCTION TO MATLAB 27 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Display formats: compact vs loose


INTRODUCTION TO MATLAB 28 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Inf & NaN

Infinity:
1/0

inf + 3
Not-a-Number (NaN):
0/0
INTRODUCTION TO MATLAB 29 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Variables: Storing data

Save value in a variable:


x=3 = Assignment
x = 4 (over-ridden) operator

Variables are case-sensitive:


T=2
t=3
Z = t+T;
INTRODUCTION TO MATLAB 30 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Variables: Naming rules


1. May consist of:
 letters A-Z, a-z
 digits 0-9
 underscore ( _ )

2. Must start with a letter.

3. Variable names are case-sensitive

4. Can be up to 63 characters long

5. Avoid using the built-in functions as the variable


name e.g. cos, sin, sqrt etc.
INTRODUCTION TO MATLAB 31 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Variables: Predefined keywords that can not be used as


variable name

break for
case function end
catch global return
classdef if spmd
continue otherwise switch
else parfor try
elseif persistent while
INTRODUCTION TO MATLAB 32 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Variables: Predefined variables

ans
pi

INTRODUCTION TO MATLAB 33 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Elementary math built-in functions

A function has a name and an argument in parentheses.

a= 4
a = sqrt(4)
INTRODUCTION TO MATLAB 34 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Elementary functions in MATLAB: Trigonometry


Function Description Example
>> sin(pi/6)
sin(x) Sine of angle x (x in radians).
ans =
sind(x) Sine of angle x (x in degrees).
0.5

cos(x) Cosine of angle x (x in radians). >> cosd(30)


cosd(x) Cosine of angle x (x in degrees). ans =
0.86603

tan(x) Tangent of angle x (x in radians). >> tan(pi/6)


tand(x) Tangent of angle x (x in degrees). ans =
0.57735
>> cotd(30)
cot(x) Cotangent of angle x (x in radians).
ans =
cotd(x) Cotangent of angle x (x in degrees).
1.7321
INTRODUCTION TO MATLAB 35 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Elementary functions in MATLAB: Trigonometry

• Inverse trigonometric functions are:

asin(x), acos(x), atan(x), acot(x) for the angle in


radians.
asind(x), acosd(x), atand(x),acotd(x) for the angle
in degrees.

•Hyperbolic trigonometric functions are

sinh(x), cosh(x), tanh(x), and coth(x).


INTRODUCTION TO MATLAB 36 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Elementary functions in MATLAB: Exponential

Function Description Example


>> sqrt(81)
sqrt(x) square root ans =
9
>> nthroot(80,5)
nthroot(x,n) Real nth root of a real number x. ans =
2.4022
>> exp(5)
exp(x) Exponential ex ans =
148.41
>> log(1000)
log(x) Natural logarithm. ans =
Base e logarithm (ln). 6.9078
>> log10(1000)
log10(x) Base 10 logarithm. ans =
3
INTRODUCTION TO MATLAB 37 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Elementary functions in MATLAB: Rounding & Remainder


Function Description Example
>>
round(3/2)
round(x) Rounds to the nearest integer.
ans =
2
>> fix(3/2)
fix(x) Rounds towards zero. ans =
1
>>
ceil(3/2)
ceil(x) Rounds towards +ve infinity.
ans =
2
>>
floor(3/2)
floor(x) Rounds towards -ve infinity.
ans =
1
>>
rem(35,3)
rem(x,y) Returns the remainder after x is divided by y.
ans =
2
>> sign(5)
sign(x) Signum function. Returns 1 if x > 0, -1 if x < -1 & 0 if x = 0 ans =
1
INTRODUCTION TO MATLAB 38 of 38
INTRO | COMMAND WINDOW | COMMAND HISTORY | ARITHMETIC | VARIABLES | FUNCTIONS

Practice …..

fix and rem


Converting 40 inches to feet-inch.

feet = fix(40/12)
inches = rem(40, 12)
INTRODUCTION TO MATLAB

NED University of Engineering & Technology


Outline

• Elementary Math built-in functions

• Script files  how to write, save, and execute


simple MATLAB programs

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 1: Introduction)
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 8 of 18

Practice …..

fix and rem 3 feet


Converting 40 inches to feet-inch.
Manual: long division

4 inches
feet = fix(40/12)
inches = rem(40,12)
METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 9 of 18

Script File

• Script file: a sequence of MATLAB commands, called a


program.

• order of execution  order they are written

• Can be edited and executed many times.

• Can be typed and edited in any text editor and then pasted
into the MATLAB editor.

• Also called M-files because the extension .m is used when


they are saved.

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 10 of 18

Creating a Script File

Home tab  New  Script

Or

Ctrl + N

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 11 of 18

Script File

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 12 of 18

Dock the Script File

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 13 of 18

Saving the Script File

When saved, MATLAB


adds the extension .m
to the name.

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 14 of 18

Saving the Script File

*Appears next to
filename.m* when changes
are made to the saved M file

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 15 of 18

Rules for naming the Script File


Same as the rules of naming a variable:

 Must begin with a letter


 Can include digits 0-9
 Can have an underscore
 no spaces
 up to 63 characters long
 The names of user-defined variables, predefined
variables, and MATLAB commands or functions
should not be used as names of script files.

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 16 of 18

Running the Script File (1)

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 17 of 18

Running the Script File (2)

• Bring the cursor to the Editor/script file

• Press F5

METU NCC
INTRODUCTION TO MATLAB BUSHRA FATIMA
FUNCTIONS | SCRIPT FILE 18 of 18

Running the Script File (3)

• Write down the name of the


script file in the command window

• Press ENTER

METU NCC
CREATING ARRAYS

NED University of Engineering & Technology


March 15, 2019
Outline
• Arrays

• One-dimensional arrays: Vectors

• Two-dimensional arrays: Matrices

• Transpose operator

• Array addressing

• Add/Delete elements from an array

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 2: Creating Arrays)
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 3 of 47

Arrays
• Arrays: List of numbers arranged in rows and/or columns

• One-dimensional array:
 a row or a column of numbers
 Vectors

• Two-dimensional array:
 Collection of numbers arranged in rows and columns
 Matrices.

• Used to store and manipulate data

• Strings: list of characters arranged in rows and/or


columns
METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 4 of 47

Arrays
Element: A (1,2)

Order of an array (m, n)


where
m = no. of rows
n = no. of columns METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 5 of 47

One-dimensional array: Vectors

Position of a point

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 6 of 47

One-dimensional array: Vectors


Row vector:

or
Column vector:

Position of a point

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 7 of 47

Creating Vectors in MATLAB


• Elements of the vector are assigned to a
variable.

•Elements in the list are enclosed in square


brackets, not parentheses.

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 8 of 47

Creating Row Vectors in MATLAB

Elements in a row
separated by:

• comma
• space

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 9 of 47

Creating Column Vectors in MATLAB

Semi-colon (;) Enter

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 10 of 47

Creating Vectors: Colon operator (:)

First element: spacing: Last element

Brackets are optional here

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 11 of 47

Creating Vectors: Colon operator (:)

First element = 2, Spacing = 1 (by


default) , Last element = 7

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 12 of 47

Creating Vectors: Colon operator (:)

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 13 of 47

Creating Vectors: the linspace function


CAUTION: Functions are CASE-SENSITIVE!
• linspace can be used to initialize a vector of
equally spaced values

• MATLAB determines the correct spacing

• linspace(xi, xf, n)
where
xi  first element
xf  last element
n  number of elements
METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 14 of 47

Creating Vectors: the linspace function

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 15 of 47

Two-dimensional array: Matrices

• Matrices: numbers in rows and columns

• Store information like in a table

• A= [1st row elements; second row


elements; 3rd row elements]

• All the rows must have the same


number of elements
METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 16 of 47

Writing a matrix in MATLAB

Separating Rows: by a semi-colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 17 of 47

Writing a matrix in MATLAB

Separating Rows: by Enter

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 18 of 47

Writing a matrix in MATLAB

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 19 of 47

Zeros and ones command

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 20 of 47

eye command

• Square matrix
• Identity matrix

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 21 of 47

eye command

First 4 rows=
4×4 identity

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 22 of 47

eye command

First 4 rows=
4×4 identity

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 23 of 47

Transpose Operator (’)


• The transpose operator switches a row to
a column and vice-versa.

• The transpose operator is applied:


’ following the variable to be
transposed.
Command transpose(A)

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 24 of 47

Transposing Vector (’)

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 25 of 47

Transposing Matrices

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 26 of 47
.

Array addressing

Element: A (1,2)

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 27 of 47
.

Array addressing

Change to 8

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 28 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 29 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 30 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 31 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 32 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 33 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 34 of 47
.

Array addressing: using a colon

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 35 of 47
.

Array addressing: using a colon and use of end

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 36 of 47
.

Array addressing: element by element

Element numbering:
column by column

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 37 of 47

Adding elements to a vector

Adding 6 elements starting with the 5th.

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 38 of 47

Adding elements to a vector

• Assign a value to the 8th element.

MATLAB assigns zeros to the 6th through 7th elements.


METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 39 of 47

Appending existing Vectors

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 40 of 47

Appending existing Vectors

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 41 of 47

Appending existing Vectors

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 42 of 47

Adding elements to a matrix

Adding elements to the 3rd row

Adding elements to the 4th


column

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 43 of 47

Adding elements to a matrix

Assign values to the 4th


row, all columns element

MATLAB changes the matrix size to 4 x 3,


and assigns zeros to the new elements.

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 44 of 47

Appending existing matrices

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 45 of 47

Deleting elements from a vector

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 46 of 47

Deleting elements from a vector

METU NCC
CREATING ARRAYS BUSHRA FATIMA
ARRAYS | VECTORS | MATRICES | TRANSPOSE | ADDRESSING AN ARRAY | ADD/DELETE 47 of 47

Deleting elements from a matrix

METU NCC
MATHEMATICAL OPERATIONS WITH
ARRAYS

Bushra Fatima
NED University of Engineering & Technology
May 13 2020
Outline
• Addition and Subtraction

• Multiplication

• Division

• Element by Element operations

• Built-in Math functions

 Using arrays

 For analyzing arrays


Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2017. (Chapter 3: Mathematical operations with arrays)
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 3 of 37

Addition & Subtraction


Addition (+) & Subtraction (-):

• Adding/subtracting arrays of identical size

• Adding/subtracting a scalar to an array

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 4 of 37

Addition of same size arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 5 of 37

Subtraction of same size arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 6 of 37

Add/Subtract of different size arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 7 of 37

Adding/Subtracting a Scalar

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 8 of 37

Adding/Subtracting a Scalar

The colon operator(:) has a lower precedence than the


plus operator (+)
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 9 of 37

Adding/Subtracting a Scalar
Precedence Operation

First Parentheses, evaluated starting with the innermost


pair
Second Exponentiation
Third Multiplication and division with equal precedence
Fourth Addition and subtraction with equal precedence

Fifth Colon Operator (in Arrays)

The colon operator(:) has a lower precedence than the


plus operator (+)
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 10 of 37

Array Multiplication
Multiplication operator (*)

Condition A*B:
A=(𝑟𝐴 , 𝑐𝐴 ) 𝐵=(𝑟𝐵 , 𝑐𝐵 )

• 𝑐𝐴 = 𝑟𝐵

• Resultant matrix dimensions: (𝑟𝐴 , 𝑐𝐵 )


METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 11 of 37

Array Multiplication

4x3 3x2
𝑐𝐴 = 𝑟𝐵
(𝑟𝐴 , 𝑐𝐵 ) = (4 , 2)
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 12 of 37

Array Multiplication

3x3 3x2 3 x2
1 4 3 5 4 1.5 + 4.1 + 3.2 (1.4 + 4.3 + 3.6)
2 6 1 1 3 = 2.5 + 6.1 + 1.2 (2.4 + 6.3 + 1.6)
5 2 8 2 6 5.5 + 2.1 + 8.2 (5.4 + 2.3 + 8.6)

15 34
= 18 32
43 74
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 13 of 37

Array Multiplication
• If A & B are square matrices

• C=A*B will also be a square matrix

• size of A = size of B = size of C

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 14 of 37

Array Multiplication

3x3

3x3

3x3

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 15 of 37

Array Multiplication
Multiplication of matrices is not commutative
A*B ≠ B*A

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 16 of 37

Array Multiplication

Power operation  Square matrix

2x3 * 2x3

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 17 of 37

Vector Multiplication: row x column


• Same no of elements

• One is a row vector; the other a column vector

Scalar product

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 18 of 37

Vector Multiplication: : row x column


Scalar product
Function

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 19 of 37

Vector Multiplication: column x row


3 elements 3 elements

3 x3 matrix

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 20 of 37

Vector Multiplication: with a scalar

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 21 of 37

Matrix Multiplication: with a scalar

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 22 of 37

Identity matrix
• square matrix

• diagonal elements are 1s

• rest of the elements are 0s

• 𝐴∗𝐼 =𝐴

• Command in MATLAB  eye

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 23 of 37

Identity matrix

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 24 of 37

Identity matrix

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 25 of 37

Inverse of a matrix
• The matrix B is the inverse of the matrix A if, when the
two matrices are multiplied, the product is the identity
matrix.

• Both matrices must be square and the multiplication order


can be BA or AB.
𝐵𝐴 = 𝐴𝐵 = 𝐼
−1
The inverse of a matrix A is typically written as 𝐴
A matrix has an inverse only when.

 It is a square matrix

 determinant ≠ zero. METU NCC


MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 26 of 37

Inverse of a matrix: inv(A) function

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 27 of 37

Inverse of a matrix: A^-1

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 28 of 37

Determinant of a matrix
• a number associated with each square matrix.

• Typically denoted by:

 det(A) or
 |A|

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 29 of 37

Determinant of a matrix: det(A)

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 30 of 37

Array Division
MATLAB has two types of array division:

 Left division \

 Right division /

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 31 of 37

Left Division \
The left division is used to solve the matrix equation

𝐴𝑋 = 𝐵 x =B/A
where X and B are column vectors.

−1 −1 −1
𝐴 𝐴𝑋 = 𝐴 𝐵 𝐼. 𝑋 = 𝐴 𝐵
𝑋= −1
𝐴 𝐵
In MATLAB the last equation can be written using the left
division character \
𝑋 = A\B METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 32 of 37

Right Division /
The right division is used to solve the matrix equation

𝑋𝐶 = 𝐷
Where X and D are row vectors.

−1 −1 −1
𝑋. 𝐶𝐶 = 𝐷. 𝐶  𝑋 = 𝐷. 𝐶
In MATLAB the last equation can be written using the right
division character /:
𝑋 = 𝐷/C
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 33 of 37

3 Linear Equations using left division


4𝑥 − 2𝑦 + 6𝑧 = 8
2𝑥 + 8𝑦 + 2𝑧 = 4
6𝑥 + 10𝑦 + 3𝑧 = 0
𝐴𝑋 = 𝐵
4 −2 6 𝑥 8
2 8 2 𝑦 = 4
6 10 3 𝑧 0
X and B are column vectors
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 34 of 37

3 Linear Equations using left division

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 35 of 37

3 Linear Equations using right division


4𝑥 − 2𝑦 + 6𝑧 = 8
2𝑥 + 8𝑦 + 2𝑧 = 4
6𝑥 + 10𝑦 + 3𝑧 = 0
𝑋𝐶 = 𝐷
4 2 6
𝑥 𝑦 𝑧 −2 8 10 = 8 4 0
6 2 3

X and D are row vectorsMETU NCC


MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 36 of 37

3 Linear Equations using right division

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ADD & SUBTRACT | MULTIPLY | DIVIDE 37 of 37

Inverse functions versus division operators


• Last two operations appear to give the same result.

• In the first, MATLAB calculates 𝐴−1 (or 𝐶 −1 ) and then uses it


to multiply B (or D).

• In the second (left division or right division), the solution X is


obtained numerically with a method that is based on Gauss
elimination.

• The division method is recommended for solving a set of


linear equations because the calculation of the inverse may be
less accurate than the Gauss elimination method when large
matrices are involved.

METU NCC
CREATING ARRAYS

Bushra Fatima
NED University of Engineering & Technology
May 12, 2020
Outline
• Built-in MATLAB functions for arrays

• Strings

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 2: Creating Arrays)
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 3 of 18

Built-in functions for handling arrays


Function Description Example
>> A=[1:6]
A=
Returns the number of elements in 1 2 3 4 5 6
length(A)
the vector A. >> length(A)
ans =
6
>> A=[1:6;7:12;13:18]
A=
1 2 3 4 5 6
Returns a row vector [m ,n ], where
7 8 9 10 11 12
size(A) m and n are the size m x n of the
13 14 15 16 17 18
array A.
>> size(A)
ans =
3 6

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 4 of 18

Built-in functions for handling arrays


Function Description Example
>> A=[1:3;4:6;7:9]
A=
1 2 3
4 5 6
When A is a matrix, creates a
7 8 9
diag(A) vector from the diagonal elements
>> diag(A)
of A.
ans =
1
5
9
A=[1:3;4:6]
A=
Returns a row vector with the 1 2 3
min(A) minimum value in each column of 4 5 6
matrix A >> a=min(A)
a=
1 2 3 METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 5 of 18

Built-in functions for handling arrays


Function Description Example
>> A=[1:3;4:6]
A=
Returns a row vector with the 1 2 3
max(A) maximum value in each column of 4 5 6
matrix A >> max(A)
ans =
4 5 6
>> A=[1:3;4:6]
A=
1 2 3
Returns a row vector with the
mean(A) 4 5 6
mean of each column of matrix A
>> mean(A)
ans =
2.5000 3.5000 4.5000

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 6 of 18

Built-in functions for handling arrays


Function Description Example
>> A=magic(3)
A=
8 1 6
Returns a row vector with the sum 3 5 7
sum(A)
of each column of matrix A 4 9 2
>> sum(A)
ans =
15 15 15
>> A=magic(3)
A=
8 1 6
Returns a row vector with the
3 5 7
Prod(A) product of each elements in each
4 9 2
column of matrix A
>> prod(A)
ans =
96 45 84 METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 7 of 18

Built-in functions for handling arrays


Function Description Example
>> A=magic(3)
A=
8 1 6
3 5 7
Returns a column vector with the
4 9 2
sum(A,2) sum of each elements in each row
>> sum(A,2)
of matrix A
ans =
15
15
15
>> A=magic(3)
A=
8 1 6
3 5 7
Returns a column vector with the
4 9 2
Prod(A,2) product of each elements in each
>> prod(A,2)
row of matrix A
ans =
48
105
72
METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 8 of 18

Strings
• an array of characters.

• ‘ strings ’

• Can include:
 Letters  Other symbols
 Digits  Spaces

• Eg. ‘ad ef’ ‘3%fr2* ‘{whatever!!}’

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 9 of 18

Strings

maroon with the first single quote purple with the last single quote

Output

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 10 of 18

Purposes of Strings (1)


• Display text messages

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 11 of 18

Purposes of Strings (2)-Chap 5


• Formatting plots e.g adding labels to axes

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 12 of 18

Purposes of Strings (2)


• Formatting plots e.g adding labels to axes

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 13 of 18

Purposes of Strings (3)-chap 7

• Input arguments of functions

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 14 of 18

Strings stored in a variable

No. of characters  14

• When a variable is defined as a string, the characters of the string


are stored in an array just as numbers are.

• Each character, including a space, is an element in the array.

• a one-line string:
 a row vector
 No.of elements = no. of characters

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 15 of 18

Addressing an element in a string

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 16 of 18

String in a matrix

METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 17 of 18

String in a matrix and use of function char

• A variable named biodata is assigned 3 rows of strings,


each with different length.

• The function char creates an array with 3 rows with the


same length as the longest row by adding empty spaces to the
shorter lines.
METU NCC
CREATING ARRAYS BUSHRA FATIMA
FUNCTIONS | STRINGS 18 of 18

Strings stored in a variable

• The variable x can be used in


mathematical expressions, while the
variable y cannot.

METU NCC
MATHEMATICAL OPERATIONS WITH
ARRAYS

Bushra Fatima
NED University of Engineering & Technology
June 17, 2020
Outline
• Element by Element operations

• Built-in Math functions

 Using arrays

 For analyzing arrays

Textbook: A. Gilat, Matlab: An Introduction with Applications 4th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 3: Mathematical operations with arrays)
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 3 of 21

Element by Element Operations


•Addition and subtraction are already element-
by-element operations.

•Can be done only with arrays of the same size.

•Element-by-element
. multiplication, division, or
exponentiation of two vectors or matrices is
entered in MATLAB by typing a period . in front
of the arithmetic operator.
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 4 of 21

Element by Element Operations

Symbol Description
.* Element by element Multiplication
.^ Element by element Exponentiation
./ Element by element Right Divison
. .\ Element by element Left Divison

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 5 of 21

Element by Element Operations

𝑎 = [𝑎1 𝑎2 𝑎3 𝑎4 ] b= [𝑏1 𝑏2 𝑏3 𝑏4 ]

𝑎.∗ 𝑏 = [𝑎1 𝑏1 𝑎2 𝑏2 𝑎3 𝑏3 𝑎4 𝑏4 ]
𝑎./𝑏 = [𝑎1 /𝑏1 𝑎2 /𝑏2 𝑎3 /𝑏3 𝑎4 /𝑏4 ]
.

𝑎. \𝑏 = [𝑏1 /𝑎1 𝑏2 /𝑎2 𝑏3 /𝑎3 𝑏4 /𝑎4 ]


𝑎. ^𝑏 = [ 𝑎1 𝑏1 𝑎2 𝑏2 𝑎3 𝑏3 𝑎4 𝑏4 ]
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 6 of 21

Array product

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 7 of 21

Element by Element right division

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 8 of 21

Element by Element Exponentiation

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 9 of 21

Application: Formula Vectorization


Calculating the value of a function at many values of its
argument:
𝑧 3 + 5𝑧
Evaluate  𝑦 = 2
4𝑧 − 10
For these values of z  z= 1 3 5 7 9 11
.

The feature of MATLAB in which arrays can be


used as arguments in functions is called
vectorization.
METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 10 of 21

Application: Formula Vectorization

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 11 of 21

Application: Formula Vectorization


Find the balances for a single amount A ($1000) over 1, 5, 10, 15,
and 20 years with the annual compound interest of 9 %.

𝐵 =𝑃 1+𝑟 𝑡

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 12 of 21

Application: Scalar product


𝑥. 𝑦 = 𝑥𝑖 𝑦𝑖
𝑖

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 13 of 21

Using Arrays in Built-in Math functions


• If the argument is an array, the operation that is
defined by the function is executed on each
element of the array.

• The output from such an operation is an array in


which each element is calculated by entering the
corresponding
. element of the argument array into
the function.

• The feature of MATLAB in which arrays can be


used as arguments in functions is called
vectorization. METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 14 of 21

Using vectors in Built-in Math functions

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 15 of 21

Using matrices in Built-in Math functions

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 16 of 21

Built-in Math functions for analyzing arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 17 of 21

Built-in Math functions for analyzing arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 18 of 21

Built-in Math functions for analyzing arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 19 of 21

Built-in Math functions for analyzing arrays

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 20 of 21

Built-in Math functions  sort


A vector or matrix can be sort in ascending or descending order.

METU NCC
MATHEMATICAL OPERATIONS WITH ARRAYS BUSHRA FATIMA
ELEMENT BY ELEMENT OPERATIONS | FUNCTIONS 21 of 21

Built-in Math functions  sort


A vector or matrix can be sort in ascending or descending order.

METU NCC
CHAPTER # 4
USING SCRIPT FILES & MANAGING DATA

Bushra Fatima
NED University of Engineering & Technology
June 18, 2020
Outline
 MATLAB workspace and window

 Input to a Script File

 Output Commands:

 The disp command


 The fprintf command

Textbook: A. Gilat, Matlab: An Introduction with Applications 4th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 4: Using Script Files & Managing Data)
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 3 of 30

MATLAB workspace and window


 MATLAB workspace consists of the set of
variables:

• defined in the command window


• defined when the script files are executed

 Variables can also be defined in a function


file but the variables defined there are saved
in a separate workspace
METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 4 of 30

The workspace window

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 5 of 30

The Variable Editor Window

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 6 of 30

The Variable Editor Window

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 7 of 30

Input to a Script File


 When a script file is executed, the variables must be in the
workspace.

 The assignment of a value to a variable can be done in 3


ways:

1. Defined and assigned a value in the script file

2. Defined and assigned a value in the command window

3. Defined in the script file but assigned a value in the


command window  input command

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 8 of 30

Input to a Script File (1)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 9 of 30

Input to a Script File (2)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 10 of 30

Input to a Script File (3)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 11 of 30

Input to a Script File (3)-typing a string

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 12 of 30

Input to a Script File (4)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 13 of 30

Input to a Script File (5)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 14 of 30

Output commands: automatic display

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 15 of 30

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 16 of 30

Output commands: disp command


Command Description
disp(A) Displays the contents, but
not the name of the array
A
disp(‘text’) Displays the text string
enclosed within the single
quotes
disp(‘ ’) Displays an empty line
disp([‘text’,num2str(A)]) Displays the text string
and the contents of array
in a single line METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 17 of 30

Output commands: disp command (1)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 18 of 30

Output commands: disp command (2)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 19 of 30

Output commands: disp command (3)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 20 of 30

Output commands: disp command (4)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 21 of 30

Output commands: disp command (5)

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 22 of 30

Output commands: fprintf command (1)


• The fprintf statement is much more flexible (and
therefore more complicated!) than disp.

• The fprintf command can be used to display output


(text and data) on the screen.

• With this command (unlike with the disp command) the


output can be formatted.

• Text and numerical values of variables can be


intermixed and displayed in the same line.

• The format of the numbers can be controlled. METU NCC


USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 23 of 30

Output commands: fprintf command (2)

1. Display text messages

2. Display text with numeric value

3. Format the display of numbers

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 24 of 30

fprintf command: text messages (1)

Next command
METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 25 of 30

fprintf command: escape character \n


‘line feed’

Other escape characters that can be inserted within


the string are:
\b Backspace.
\t Horizontal tab.
METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 26 of 30

fprintf command: escape character \b


‘backspace’

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 27 of 30

fprintf command: text + numeric

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 28 of 30

fprintf command: text + numeric

METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 29 of 30

fprintf command: text + numeric

i or d
S string
METU NCC
USING SCRIPT FILES & MANAGING DATA BUSHRA FATIMA
WORKSPACE | INPUT | OUTPUT 30 of 30

fprintf command: text + numeric

METU NCC
PROGRAMMING WITH MATLAB
RELATIONAL & LOGICAL OPERATORS

Bushra Fatima
NED University of Engineering & Technology
June 23, 2020
Outline

• Introduction

• Tools to control the flow of program

• Relational Operators

• Logical Operators

Textbook: A. Gilat, Matlab: An Introduction with Applications 4th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 6: Programming with MATLAB)
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 3 of 29

Introduction
• A computer program is a sequence of computer
commands.

• Simple execution:
Order of execution  order they are typed.

• Not so simple:
Example: cost of a mailing package

• Repeat a sequence of commands several times within a


program.

Example: Iteration problems


METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 4 of 29

Relational & Logical Operators


•Changing the flow of a program requires some
kind of decision-making process within the
program.

•Decision: whether to execute the next command


or skip it.

•Decision based on: comparing values of


variables.

•Decision Tool: relational and logical operators


METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 5 of 29

Relational Operators
• A relational operator compares two numbers by
determining whether a comparison statement is true
(1) or false (0).

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 6 of 29

Relational Operators (2)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 7 of 29

Relational Operators (3)

CAUTION: No space between them!

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 8 of 29

Relational Operators (3)

CAUTION: No space between them!

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 9 of 29

Array comparison
element-by-element comparison

Logical
Array
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 10 of 29

Array comparison (2)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 11 of 29

Scalar comparison with array

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 12 of 29

Use in Mathematical expressions

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 13 of 29

Logical Vectors  array addressing


•The results of a relational operation with vectors,
which are vectors with 0s and 1s, are called
logical vectors and can be used for addressing
vectors.

•When a logical vector is used for addressing


another vector, it extracts from that vector the
elements in the positions where the logical
vector has 1s.

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 14 of 29

Logical Vectors  array addressing

Array addressing

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 15 of 29

Numerical arrays | Logical arrays


•Numerical arrays with the numbers 0s and 1s ≠
logical arrays with 0s and 1s.

•Numerical arrays can not be used for


addressing.

•Logical arrays can be used in arithmetic


operations.

•The first time a logical array is used in arithmetic


operations it is changed to a numerical array.
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 16 of 29

Order of precedence
Precedence Operation

First Parentheses, evaluated starting with the innermost


pair
Second Exponentiation
Third Multiplication and division with equal precedence
Fourth Addition and subtraction with equal precedence

Fifth Colon Operator (in Arrays)

Sixth Relational Operators


(<, >, ==, ~=, >=, <=)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO | RELATIONAL OPERATORS | LOGICAL OPERATORS 17 of 29

Order of precedence

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 18 of 29

Logical Operators (1)


• A logical operator examines true/false statements and produces
a result that is true (1) or false (0) according to the specific
operator.

• Logical operators have numbers as operands.

• A non-zero number is true, and a zero number is false.

• Logical operators (like relational operators) are used as:


 arithmetic operators within a mathematical expression.
 The result can be used in other mathematical operations, in
addressing arrays, and together with other MATLAB
commands (e.g., if) to control the flow of a program.
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 19 of 29

Logical Operators (2)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 20 of 29

Order of Precedence

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 21 of 29

Logical Operators with scalars


3 & 7 are both true (non-zero),
hence 1

Since at least 1 number is true

Since 25 is non-zero (true) hence


the opposite is false (0)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 22 of 29

Use in Mathematical Expressions

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 23 of 29

Logical Operators with arrays (&)


Defining 2 vectors

1 when both x & y are non-zero elements

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 24 of 29

Logical Operators with arrays (|)


Defining 2 vectors

1 when either or both x and y are non-zero


elements

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 25 of 29

Logical Operators with arrays (~)


Defining a vector

0 where the vector (x) has a non-zero


element

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 26 of 29

Logical Operation between a scalar and an array

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 27 of 29

Mathematical operations: relational & logical operators

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 28 of 29

Mathematical operations: relational & logical operators

-5<x=1
1<-1=0

-5<x=1
-2<-1=11
1&1=1

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
INTRO| RELATIONAL OPERATORS | LOGICAL OPERATORS 29 of 29

Mathematical operations: relational & logical operators

y<7=1 ~y=0
~1=0 0<7=1

y>=8=0
x<-1=1
0|1=1
~1=0 METU NCC
PROGRAMMING WITH MATLAB
LOGICAL FUNCTIONS
CONDITIONAL STATEMENTS

Bushra Fatima
NED University of Engineering & Technology June 29, 2020
OUTLINE
1. LOGICAL FUNCTIONS

2. CONDITIONAL STATEMENTS
1. if – end STRUCTURE
2. if – else - end STRUCTURE
3. if – elseif – else - end STRUCTURE

Textbook: A. Gilat, Matlab: An Introduction with Applications 4th Edition. John Wiley &
Sons, Incorporated, 2016. (Chapter 6: Programming with MATLAB)
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 3 of 16

Built-in Logical Functions (and, or, not)


MATLAB has built-in functions that are
equivalent to the logical operators:

1. and(A,B) = A&B

2. or(A,B)=A|B

3. not(A)=~A

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 4 of 16

Other built-in Logical Functions (1)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 5 of 16

Other built-in Logical Functions (2)

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 6 of 16

Truth Table

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 7 of 16

CONDITIONAL STATEMENT

• Decision-making command:
• execute the command
• or to skip the command

• In a conditional statement, a conditional expression is


stated.

• True (1), a group of commands that follow the


statement are executed.

• False (0), the computer skips the group.

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 8 of 16

If-end statement flowchart

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 9 of 16

If-end statement

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 10 of 16

If-else-end statement flowchart

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 11 of 16

If-else-end statement

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 12 of 16

If-elseif-else-end statement flowchart

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 13 of 16

If elseif  else  end

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 14 of 16

If elseif elseif  end

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 15 of 16

Exercise

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOGICAL FUNCTIONS | IF-END | IF-ELSE-END | IF-ELSEIF-ELSE-END 16 of 16

Exercise

METU NCC
PROGRAMMING WITH MATLAB
SWITCH STATEMENTS

Bushra Fatima
NED University of Engineering & Technology
July 4, 2020
Outline

• Switch statement

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 6: Programming with MATLAB)
switch statement

The value of the switch expression in the switch command is


compared with the values that are next to each of the case
statements.

If a match is found, the group of commands that follow the case


statement with the match are executed.
switch statement structure
switch statement structure
Practice Question
The following are formulas for calculating the training heart rate (THR) for
men and women

For men (Karvonen formula):


THR = [ ( 220 - AGE) – RHR ] x INTEN + RHR

For women:
THR = [ ( 206 - 0.88 x AGE )-RHR ] x INTEN + RHR

where AGE is the person’s age, RHR the resting heart rate, and INTEN the fitness
level (0.55 for low, 0.65 for medium, and 0.8 for high fitness). Write a
program in a script file that determines the THR. The program asks users to
enter their gender (male or female), age (number), resting heart rate (number),
and fitness level (low, medium, or high). The program then displays the training
heart rate. Use the program for determining the training heart rate for the
following two individuals:
(a) A 21-years-old male, resting heart rate of 62, and low fitness level.
(b) A 19-years-old female, resting heart rate of 67, and high fitness level.
Method 1: Using input function with switch
Method 1: Using input function with switch
Method 2: Using menu function with switch
Method 2: Using menu function with switch
PROGRAMMING WITH MATLAB
FOR LOOP

Bushra Fatima
NED University of Engineering & Technology
July 07, 2020
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOPS | FOR LOOP 2 of 14

Determinate & Indeterminate Loops  Repetition


• A loop alters 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.


• In each pass at least one variable, but usually more than one, or even
all the variables that are defined within the loop, are assigned new
values.

• MATLAB has two kinds of loops.


o Determinate loop: for-end Loops (known number of passes).
o Indeterminate loop: while-end loops (unknown number of
passes).

• Both kinds of loops can be terminated at any time with the break
command METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 3 of 14

for-end loops

Structure of for-end loops


𝒕−𝒇
𝐢𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝐨𝐫 𝐭𝐫𝐢𝐩 𝐜𝐨𝐮𝐧𝐭 = 𝐟𝐥𝐨𝐨𝐫 +𝟏
𝒔

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 4 of 14

Structure of for-end loops


• k = 25:–5:10  k = 25, 20, 15, 10

• k = 3:7  k = 3, 4, 5, 6, 7

• k = 8:10:50  k = 8, 18, 28, 38, 48

• k = [7 9 –1 3 3 5]

• If f = t, the loop is executed once


METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 5 of 14

Structure of for-end loops

• Loop is not executed (for k=f:s:t) when


o f>t&s>0
o f<t&s<0

𝐢𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝐨𝐫 𝐭𝐫𝐢𝐩 𝐜𝐨𝐮𝐧𝐭


𝟗−𝟐
= 𝐟𝐥𝐨𝐨𝐫 +𝟏<𝟎
−𝟐

𝐢𝐭𝐞𝐫𝐚𝐭𝐢𝐨𝐧 𝐨𝐫 𝐭𝐫𝐢𝐩 𝐜𝐨𝐮𝐧𝐭


−𝟗 + 𝟐
= 𝐟𝐥𝐨𝐨𝐫 +𝟏<𝟎
𝟐
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 6 of 14

Structure of for-end loops


• The value of k should not be redefined within the
loop.

• Each for command in a program must have an


end command.

• The value of the loop index variable (k) is not


displayed automatically.

• It is possible to display the value in each pass


(which is sometimes useful for debugging) by
typing k as one of the commands in the loop.
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 7 of 14

Structure of for-end loops

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 8 of 14

Structure of for-end loops

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 9 of 14

Structure of for-end loops

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 10 of 14

Program example for-end loops

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 11 of 14

Avoiding for loops by vectorizing

•Element-by element operations with arrays are


one of the superior features of MATLAB that
provide the means for computing in
circumstances that otherwise require loops.

•element-by-element operations are faster than


loops and are recommended when either
method can be used.
METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 12 of 14

Sum of series: sample problem 6-5

Use a for-end loop in a script file to


calculate the sum of the first n terms of
the series:
𝑛 𝑘
(−1) 𝑘
2𝑘
𝑘=1
Execute the script file for n = 4.

Do NOT use the function sum


METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 13 of 14

Program for-end loops: sum of series

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP 14 of 14

sum of series: by element by element operation

METU NCC
PROGRAMMING WITH MATLAB
FOR LOOPS

Bushra Fatima
NED University of Engineering & Technology
July 13, 2020
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 2 of 11

Program for-end loops: factorial

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 3 of 11

Sample problem 6-6: modify vector elements


A vector is given by
V = [5, 17, –3, 8, 0, –7, 12, 15, 20, –6, 6, 4, –7, 16].

Write a program as a script file that


1. doubles the elements that are positive and are
divisible by 3 or 5, and,
2. raises to the power of 3 the elements that are
negative but greater than –5.

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 4 of 11

Sample problem 6-6

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 5 of 11

Sample problem 6-6

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 6 of 11

Sample problem 6-6: method 2

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 7 of 11

Sample problem 6-6: method 2

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 8 of 11

Review problem 6.8: Problem 12

Fibonacci numbers are the numbers in a sequence in


which the first three elements are 0, 1, and 1, and the
value of each subsequent element is the sum of the
previous three elements:
0, 1, 1, 2, 4, 7, 13, 24, ...
Write a MATLAB program in a script file that determines
and displays the first 25 Fibonacci numbers

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 9 of 11

Review problem 6.8: Problem 12

0, 1, 1, 2, 4, 7, 13, 24, ...

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 10 of 11

METU NCC
PROGRAMMING WITH MATLAB BUSHRA FATIMA
LOOP | FOR LOOP | WHILE LOOP | NESTED LOOP 11 of 11

METU NCC
PROGRAMMING WITH MATLAB
WHILE LOOPS

Bushra Fatima
NED University of Engineering & Technology
July 14, 2020
while-end loops

• while-end loops when repetition is required 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 until a stated


condition is satisfied.
Structure of a while-end loop
Structure of a while-end loop

The conditional expression in the while


command must include at least one
variable.
The variables in the conditional
expression must have assigned values
when MATLAB executes the while
command for the first time.
Structure of a while-end loop
• At least one of the variables in the conditional
expression must be assigned a new value in the
commands that are between the while and the end.

• Otherwise, once the looping starts it will never stop


since the conditional expression will remain true.

Indefinite loop: ctrl+c


while-end loop: sample problem 6-7

Write a program in a script file that determines 𝑒 𝑥 by


using the Taylor series representation.

The function 𝑒 𝑥 can be represented in a Taylor series


by


𝑥
𝑥𝑛 𝑥2 𝑥3
𝑒 = =1+𝑥+ + +⋯
𝑛! 2! 3!
𝑛=0
while-end loop: sample problem 6-7
Use the program to calculate: 𝑒 2 :
Program flow:
• The program calculates 𝑒 2 by adding terms of the series
and stopping when the absolute value of the term that
was added last is smaller than 0.0001.
• Use a while-end loop, but limit the number of passes to
30.
• If in the 30th pass the value of the term that is added is
not smaller than 0.0001, the program stops and displays a
message that more than 30 terms are needed.
while-end loop: sample problem 6-7
while-end loop: testing prime numbers
PROGRAMMING WITH MATLAB
NESTED LOOPS

Bushra Fatima
NED University of Engineering & Technology
July 19, 2020
Nested loops

• Loops and conditional statements can be nested within other loops


or conditional statements.

• This means that a loop and/or a conditional statement can start (and
end) within another loop or conditional statement.

• There is no limit to the number of loops and conditional statements


that can be nested.

• It must be remembered, however, that each if, case, for, and while
statement must have a corresponding end statement.
Nested loops
Nested loops: Review Problem 8

Use loops to create a 4 x 3 matrix in


which the value of each element is the
sum of its row number and its column
number divided by the square of its
column number.
For example, the value of element
(2,3) is (2 + 3) ⁄ 32 = 0.5555.
Nested loops: Review Problem 8

Column (j )
1 2 3
2 2 2
1 (1+1)/1 (1+2)/2 (1+3)/3
2 2 2
2 (2+1)/1 (2+2)/2 (2+3)/3
Row (i ) 2 2 2
3 (3+1)/1 (3+2)/2 (3+3)/3
2 2 2
4 (4+1)/1 (4+2)/2 (4+3)/3
Nested loops: Review Problem 8
break command
• break command terminates the execution of the loop

• MATLAB jumps to the end command of the loop and


continues with the next command

• If the break command is inside a nested loop, only the


nested loop is terminated.
break command
break command
continue command
• The continue command can be used inside a loop
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.

• the continue command does not execute the


remaining commands in the loop, but skips to the
end command of the loop and then starts a new
pass.
continue command

Modify vector x such that all its elements are squared


except element no 4 which is over-ridden as zero.
continue command

Modify vector x such that all its elements are squared


except element no 4 which is over-ridden as zero.
Outside nested
Loop Loop 27 19 13 5 3

1 19 27 13 5 3

2 19 13 27 5 3
1
3 19 13 5 27 3
4 19 13 5 3 27
Outside nested
Loop Loop 19 13 5 3 27
1 13 19 5 3 27
2 2 13 5 19 3 27
3 13 5 3 19 27
Outside nested
Loop Loop 13 5 3 19 27
1 5 13 3 19 27
3
2 5 3 13 19 27
Outside nested
Loop Loop 5 3 13 19 27
4 1 3 5 13 19 27
Solution
Script file:
clear, clc
BOS=[2.67 1.00 1.21 3.09 3.43 4.71 3.88 3.08 4.10 2.62 1.01 5.93];
SEA=[6.83 3.63 7.20 2.68 2.05 2.96 1.04 0.00 0.03 6.71 8.28 6.85];
disp('Part (a)')
B_T=sum(BOS);
B_A=mean(BOS);
S_T=sum(SEA);
S_A=mean(SEA);
fprintf('The total precipitation in Boston in 2012 was %.2f in',B_T)
fprintf(' and average %.2f in\n',B_A)
fprintf('The total precipitation in Seattle in 2012 was %.2f in',S_T)
fprintf(' and average %.2f in\n\n',S_A)
disp('Part (b)')
B_D=sum(BOS>B_A);
S_D=sum(SEA>S_A);
fprintf('Boston had %i months above average and Seattle %i
months\n\n',B_D,S_D)
disp('Part (c)')
BltS=sum(BOS<SEA);
m=1:12;
fprintf('The precipitation was lower in Boston in the following %i
months:',BltS)
fprintf(' %i',m(BOS<SEA))
fprintf('\n')
Command Window:
Part (a)
The total precipitation in Boston in 2012 was 36.73 in and average 3.06 in
The total precipitation in Seattle in 2012 was 48.26 in and average 4.02 in
Part (b)
Boston had 7 months above average and Seattle 5 months
Part (c)
The precipitation was lower in Boston in the following 6 months: 1 2 3 10 11
12
USER-DEFINED FUNCTIONS AND FUNCTION
FILES

Bushra Fatima
NED University of Engineering & Technology
Sept 02, 2020
Introduction
• simple function that needs to be calculated only
once  typed as part of the program.

• when a function needs to be evaluated many times


for different values of arguments, it is convenient to
create a “user-defined” function.

• Once a user-defined function is created (saved) it


can be used just like the built-in functions.
Introduction
• A user-defined function is a MATLAB program:
1. created by the user
2. saved as a function file
3. then used like a built-in function.

• The function can be:


1. a simple single mathematical expression or
2. a complicated mathematical expression involving series of
calculations.

• In many cases it is actually a subprogram within a computer


program.
Introduction
• calculations in the function file are carried out using the
input data,
• results of the calculations are transferred out of the
function file by the output.

• The input and the output can be:


1. one or several variables,
2. and each can be a scalar, a vector, or an array of any
size.
Creating a Function File
Structure of a Function File
Function Definition Line
• The first executable line in a function file must be the function definition
line.
• Otherwise the file is considered a script file.
• The function definition line:
• Defines the file as a function file
• Defines the name of the function
• Defines the number and order of the input and output arguments
The form of the function definition line is:
Input & Output arguments
The H1 Line and Help Text Lines
• Comment lines following the function definition line.
• optional.
• H1 line:
• first comment line
• contains the name
• a short definition of the function.
• When a user types lookfor a_word, MATLAB searches for a_word in the H1 lines of all the
functions, and if a match is found, the H1 line that contains the match is displayed.
• help text lines:
• Comment lines that follow the H1 line.
• These lines contain an explanation of the function and any instructions related to the
input and output arguments.
• The comment lines that are typed between the function definition line and the first non-
comment line (the H1 line and the help text) are displayed when the user types help
function_name in the Command Window.
Function Body
• Contains the computer program (code) that actually performs the
computations.

• The code can use all MATLAB programming features:

• Calculation
• Assignments
• any built-in or user-defined functions
• flow control (conditional statements and/or loops)
• Comments
• blank lines
• interactive input and output.
Local Variables
• All the variables in a function file are local (the input and output arguments and any variables
that are assigned values within the function file).
• This means that the variables are defined and recognized only inside the function file.
• When a function file is executed, MATLAB uses an area of memory that is separate from the
workspace (the memory space of the Command Window and the script files).
• In a function file the input variables are assigned values each time the function is called.
• These variables are then used in the calculations within the function file.
• When the function file finishes its execution, the values of the output arguments are
transferred to the variables that were used when the function was called.
• All this means that a function file can have variables with the same names as variables in the
Command Window or in script files.
• The function file does not recognize variables with the same names as have been assigned
values outside the function.
• The assignment of values to these variables in the function file will not change their assignment
elsewhere.
SAVING A FUNCTION FILE
• A function file must be saved before it can be used.

• Recommended  file name = function name in the function definition line.

• In this way the function is called (used) by using the function name.

• If a function file is saved with a different name, the name it is saved under must be
used when the function is called.

• Function files are saved with the extension .m.


USING A USER-DEFINED FUNCTION
• A user-defined function is used in the same way as a built-in function.

• The function can be called from the Command Window, from a script file, or from another
function.

• To use the function file, the folder where it is saved must either be in the current folder or
be in the search path
• A function can be used by assigning its output to a variable (or variables), as a part of a
mathematical expression, as an argument in another function, or just by typing its name in
the Command Window or in a script file.

• In all cases the user must know exactly what the input and output arguments are.
• An input argument can be a number, a computable expression, or a variable that has an
assigned value.

• The arguments are assigned according to their position in the input and output argument
lists in the function definition line.
Sample Problem
Sample Problem
Sample Problem’s Solution
COMPARISON
Script Files BETWEEN SCRIPT FILES AND FUNCTION FILES
Function
Both script and function files are saved with the extension .m (that is why they
are sometimes called M-files).
The first executable line in a function file must
be the function definition line.
The variables in a script file are recognized in The variables in a function file are local.
the Command Window.

Script files can use variables that have been


defined in the workspace.

• Script files contain a sequence of MATLAB Function files can accept data through input
commands (statements). arguments and can return data through
output arguments.

When a function file is saved, the name of the


file should be the same as the name of the
function
A user-defined function is used in the same
way as a built-in function. It can be used
(called) in the Command Window, in a script
file, or in another function
Anonymous function
• An anonymous function is a user-defined function that is defined and written within
the computer code (not in a separate function file) and is then used in the code.
• Anonymous functions can be defined in any part of MATLAB (in the Command
Window, in script files, and inside regular user-defined functions).
• An anonymous function is a simple (one-line) user-defined function that is defined
without creating a separate function file (m-file).
• Anonymous functions can be constructed in the Command Window, within a script
file, or inside a regular user-defined function.
Anonymous function

circle = @ (x,y) 16*x^2+9*y^2.


Anonymous function
Sample Problem 7-6: Motion of a projectile
Create a function file that calculates the trajectory of a projectile.
The inputs to the function are:
• the initial velocity 𝒗𝟎
• the angle at which the projectile is fired theta
The outputs from the function are:
• the maximum height 𝒉𝒎𝒂𝒙
• Distance 𝒅𝒎𝒂𝒙
In addition, the function generates a plot of the trajectory.
Use the function to calculate the trajectory of a projectile that is fired
at a velocity of 230 m/s at an angle of 39°.
Sample Solution 7-6: Relevant equations
Initital velocity 𝑣0 :
• Horizontal Component 𝒗𝟎𝒙 = 𝒗𝟎 𝐜𝐨𝐬 𝜽
• Vertical Component 𝒗𝟎𝒚 = 𝒗𝟎 𝐬𝐢𝐧 𝜽

Vertical direction:
𝟏
Velocity 𝒗𝒚 = 𝒗𝟎𝒚 − 𝐠𝒕 Position 𝒚 = 𝒗𝟎𝒚 𝒕 − 𝐠𝒕
𝟐

Highest Point:
𝒗𝟎𝒚 𝒗𝟐 𝟎𝒚
Velocity 𝒗𝒚 = 𝟎 Time 𝒕𝒎𝒂𝒙 = Height 𝒉𝒎𝒂𝒙 =
𝒈 𝟐𝒈

Flying time: 𝒕𝒕𝒐𝒕 = 𝟐𝒕𝒎𝒂𝒙

Horizontal distance: 𝒙 = 𝒗𝟎𝒙 𝒕𝒕𝒐𝒕


Sample Solution 7-6: Function File
function [hmax,dmax] = trajectory(v0,theta)
%function trajectory calculates:
%1. max height
%2. max horizontal distance
%3. Plot of the trajectory
% input arguments:
% 1. initial velocity in m/s
% 2. theta in degrees
% output arguments:
% 1. hmax: max height in m
% 2. dmax: max horizontal dist in m
g=9.81;
v0x=v0*cosd(theta); v0y=v0*sind(theta);
tmax=v0y/g; hmax=v0y^2/(2*g); ttot=2*tmax;
dmax=v0x*ttot;
%Trajectory plot
tplot=linspace(0,ttot,200);
x=v0x*tplot; y=v0y*tplot-0.5*g*tplot.^2;
plot(x,y)
xlabel('DISTANCE (m)'), ylabel('HEIGHT (m)')
title('PROJECTILE''S TRAJECTORY')
end
Sample Solution 7-6: Command window
Sample Solution 7-6: trajectory
TWO-DIMENSIONAL PLOTS

Bushra Fatima
NED University of Engineering & Technology
July 25, 2020
Outline

• Introduction

• Commands
• plot
• fplot

• format

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 5: Two dimensional pots)
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 3 of 37

Introduction
o Plots:
• standard plots with linear axes
• plots with logarithmic and semi-logarithmic axes
• bar and stairs plots
• polar plots
• three-dimensional contour surface
• mesh plots

o Several graphs in the same plot

o several plots can be placed on the same page.

o Multiple graphs on different figure windows


METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 4 of 37

Introduction

o Formatting of plots:.
• line type (-, - -, etc.),
• Color (r, g, b etc)
• -
thickness ( , - , etc.),
• line markers ( * , o, x etc)
• grid lines
• titles
• legends

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 5 of 37

Introduction

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 6 of 37

plot command
• The plot command is used to create 2D plots.

>> plot(x,y)
• The arguments x and y are each a vector (one-
dimensional array).

• The two vectors must have the same number of elements.

• When the plot command is executed, a figure is created in


the Figure Window

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 7 of 37

plot command
The plot command has additional, optional arguments that can be used to
specify:
• the color of the line (blue, black, red etc.)
• style of the line ( - , --, : etc. )
• type of markers ( * , + , o etc. )

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 8 of 37

Line specifiers: 1. Line style

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 9 of 37

Line specifiers: 2. Line color

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 10 of 37

Line Specifiers: 3. Marker type

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 11 of 37

Line specifiers
• The specifiers are typed inside the plot command as
‘strings’.

• Within the string the specifiers can be typed in any order.

• The specifiers are optional. This means that none, one,


two, or all three types can be included in a command

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 12 of 37

Example plots (1)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 13 of 37

Example plots (2)

2 METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 14 of 37

Example plots (3)

2
1 2 3 4 5 6 7 8 9 10
METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 15 of 37

Example plots

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 16 of 37

Property name and property value


o Properties are optional and can be used to:
o specify the thickness of the line
o the size of the marker
o colors of the marker’s edge line and fill.

• The Property Name is typed as:


• a string,
• followed by a comma and a value for the
property, all inside the plot command.

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 17 of 37

Property name and property value

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 18 of 37

Example plot
plot(x,y,‘-mo’,‘LineWidth’,2,‘markersize’,12,
‘MarkerEdgeColor’,‘g’,‘markerfacecolor’,‘y’)

• creates a plot that connects the points with a:


o magenta solid line and circles as markers at the
points.
o the line width is 2 points and
o the size of the circle markers is 12 points.
o The markers have a green edge line and yellow
filling.

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 19 of 37

Multiple graphs on the same plot (1)


• The command plot(x,y,u,v,t,h)
creates three graphs—y vs. x, v vs. u, and h vs. t—all in the
same plot.

• The vectors of each pair must be of the same length.

• MATLAB automatically plots the graphs in different colors so


that they can be identified.

• It is also possible to add line specifiers following each pair.

• For example the command plot(x,y,‘-b’,u,v,‘--r’,t,h,‘g:’)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 20 of 37

line command (Method 3)


• line  to add additional graphs (lines) to a plot that already
exists.

• Difference between the plot and line commands:


o plot command starts a new plot every time it is
executed
o line command adds lines to a plot that already exists.

• plot with several graphs: type plot command first followed


by line commands

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 21 of 37

line command
• The format of the line command is almost the same as the plot
command

line(x,y,‘PropertyName’,PropertyValue)
• (Optional) Properties with values that can be used to specify the line style,
color, and width, marker type, size, and edge and fill colors

line(x,y,‘linestyle’,‘--’,‘color’,‘r’,‘marker’,‘o’)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 22 of 37

Sample problem 5-1


Plot the function:
3
𝑦 = 3𝑥 − 26𝑥 + 10
and its first and second
derivatives,
for −2 ≤ 𝑥 ≤ 4 all in the
same plot. METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 23 of 37

Solution (method 1)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 24 of 37

Sample problem 5-1

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 25 of 37

Solution (Method 2)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 26 of 37

Solution (Method 3)

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 27 of 37

Plot of a function: fplot


The fplot command plots a function with the form between
specified limits. The command has the form:

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 28 of 37

Plot of a function: fplot


𝑦 = 𝑥 2 + 4 sin 2𝑥 − 1 for −3 ≤ 𝑥 ≤ 3

• The functions can include MATLAB built-in


functions that are created.

• The function can include previously defined


variables

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 29 of 37

Plot of a function: fplot

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 30 of 37

Plot of a function: plot

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 31 of 37

Plot of a function: fplot

• line specifiers: The line


specifiers are the same as
in the plot command.

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 32 of 37

xlabel & ylabel commands

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 33 of 37

title command

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 34 of 37

legend command

• pos = -1 Places the legend outside the axes boundaries


on the right side.
• pos = 0 Places the legend inside the axes boundaries in
a location that interferes the least with the graphs.
• pos = 1 Places the legend at the upper-right corner of
the plot (default).
• pos = 2 Places the legend at the upper-left corner of the
plot.
• pos = 3 Places the legend at the lower-left corner of the
plot.
• pos = 4 Places the legend at the lower-right corner of
the plot.
METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 35 of 37

Formatting the text


Formatting the text within the xlabel, ylabel, title, text and legend commands:

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 36 of 37

Formatting the text


Formatting the text within the xlabel, ylabel, title, text and legend commands:

Subscript and superscript:


• A single character can be displayed as a subscript by
typing _ (the underscore character)
• A single character can be displayed as a superscript
^ in front of the character, respectively.
• Several consecutive characters can be displayed as a
subscript or a superscript by typing the characters
inside braces { } following the _ or the ^.

METU NCC
TWO-DIMENSIONAL PLOTS BUSHRA FATIMA
INTRO | PLOT COMMAND | FPLOT COMMAND | FORMAT 37 of 37

Formatting the text


Formatting the text within the xlabel, ylabel, title, text and legend commands:

METU NCC
Polynomials,
Curve Fitting, and
Maxima Minima
Polynomials are mathematical expressions that are frequently used for
problem solving and modeling in science and engineering.
Curve fitting is a process of finding a function that can be used to model
data
Maximum and Minimum points of function.

Polynomial
# of elements: Degree of the polynormial + 1

Linear: 2 elements
Quadratic: 3 elements

1
Value of a Polynomial

Example

2
Roots of a Polynomial

Example

3
Roots of a Polynomial

Example

4
Addition, Multiplication, and Division of
Polynomials
Two polynomials can be added (or subtracted) by adding (subtracting)
the vectors of the coefficients. If the polynomials are not of the same
order (which means that the vectors of the coefficients are not of the
same length), the shorter vector has to be modified to be of the same
length as the longer vector by adding zeros (called padding) in front

Example

10

5
Multiplication

11

Example

12

6
Division

13

Example

14

7
Derivatives of Polynomials

15

16

8
Curve Fitting
• Curve fitting, also called regression analysis, is a process of fitting a
function to a set of data points. The function can then be used as a
mathematical model of the data. Since there are many types of
functions (linear, polynomial, power, exponential, etc.), curve fitting
can be a complicated process.

17

18

9
polyfit function

polyfit command does not plot the graph, it only i the polynomial's coefficients.

19

20

10
Example

21

Other than polynomial

22

11
log(y)=log(b) + m*log(x)
ln(y)=ln(b)+mx
log(y)=log(b)+mx

1/y=mx+b

23

24

12
Example

25

Minima

26

13
Example

27

Maxima

28

14
LAB #01
REGRESSION ANALYSIS
OR
CURVE FITTING

Bushra Fatima
NED University of Engineering & Technology August 19, 2020
Regression Analysis or Curve Fitting
•Curve fitting, also called regression analysis, is a
process of fitting a function to a set of data points.
•The function can be used as a mathematical
model of the data.
•Since there are many types of functions (linear,
polynomial, power, exponential, etc.), curve fitting
can be a complicated process.
Curve Fitting with polynomials
Polynomials can be used to fit data points in two ways.

• The polynomial passes through all the data points,


• The polynomial does not pass through any of the
points but overall gives a good approximation of the
data.
Curve Fitting with polynomials (1)
The polynomial passes through all the data points

• When n points (xi, yi) are given  polynomial of degree (n-1) that passes
through all the points.

• 2 points  linear equation 𝑦 = 𝑚𝑥 + 𝑏.


• 3 points  quadratic equation 𝑦 = 𝑎𝑥 2 + 𝑏𝑥 + 𝑐
• n points  polynomial equation 𝑦 = 𝑎𝑛−1 𝑥 𝑛−1 + 𝑎𝑛−2 𝑥 𝑛−2 + ⋯ . +𝑎1 𝑥 + 𝑎0

• The coefficients of the polynomial are determined by substituting each point


in the polynomial and then solving the n equations for the coefficients.
Curve Fitting with polynomials (2)
Polynomials that do not necessarily pass through any of the points:
Curve Fitting with polynomials (2)
Polynomials that do not necessarily pass through any of the points:

• 2 equations with 2 unknowns, 𝑎0 & 𝑎1 .


polyfit function

!!! polyfit function does NOT plot the graph. It only gives the coefficients
A set of seven points is given by (0.9, 0.9), (1.5, 1.5), (3, 2.5), (4, 5.1),(6, 4.5), (8, 4.9),
and (9.5, 6.3).

x=[0.9 1.5 3 4 6 8 9.5];


y=[0.9 1.5 2.5 5.1 4.5 4.9 6.3];
p=polyfit(x,y,3) %p=ax^3+bx^2+cx+d --coefficients only
xp=0.9:0.1:9.5;
yp=polyval(p,xp); %determines value of the polynomial
at each xp
plot(x,y,'o') %plots the scatter plot of data points
hold on
plot(xp,yp) %plots the polynomial on the same plot
xlabel('x'); ylabel('y')
Curve Fitting with functions other than polynomials
Function General Linear Form polyfit function form
Equation
Power 𝑦 = 𝑏𝑥 𝑚 ln 𝑦 = 𝑚 ln 𝑥 + ln 𝑏 p=polyfit(log(x),log(y),1)
Exponential 𝑦 = 𝑏𝑒 𝑚𝑥 ln 𝑦 = 𝑚𝑥 + ln 𝑏 p=polyfit(x,log(y),1)
𝑦 = 𝑏10𝑚𝑥 log 𝑦 = 𝑚𝑥 + log 𝑏 p=polyfit(x,log10(y),1)
logarithmic 𝑦 = 𝑚 ln 𝑥 + 𝑏 𝑦 = 𝑚 ln 𝑥 + 𝑏 p=polyfit(log(x),y,1)
𝑦 = 𝑚 log 𝑥 + 𝑏 𝑦 = 𝑚 log 𝑥 + 𝑏 p=polyfit(log10(x),y,1)
reciprocal 1 1 = 𝑚𝑥 + 𝑏 p=polyfit(x,1./y,1)
𝑦= 𝑦
𝑚𝑥 + 𝑏
Curve Fitting with functions other than polynomials
Functio Linear Form polyfit function form coefficients
n
Power ln 𝑦 = 𝑚 ln 𝑥 + ln 𝑏 p=polyfit(log(x),log(y),1) m=p(1) ; b=exp(p(2));
Exp ln 𝑦 = 𝑚𝑥 + ln 𝑏 p=polyfit(x,log(y),1) m=p(1) ; b=exp(p(2));
log 𝑦 = 𝑚𝑥 + log 𝑏 p=polyfit(x,log10(y),1)
log 𝑦 = 𝑚 ln 𝑥 + 𝑏 p=polyfit(log(x),y,1) m=p(1) ; b=p(2)
𝑦 = 𝑚 log 𝑥 + 𝑏 p=polyfit(log10(x),y,1)
reciproc 1 = 𝑚𝑥 + 𝑏 p=polyfit(x,1./y,1) m=p(1) ; b=p(2)
𝑦
al
Curve Fitting with functions other than polynomials

ln 𝑦 = 𝑚 ln 𝑥 + ln 𝑏

l𝑜𝑔 𝑦 = 𝑚𝑥 + l𝑜𝑔 𝑏
Curve Fitting with functions other than polynomials
Curve Fitting with functions other than polynomials
Solution: Scatter Plot (linear axes)

1. Linear function
2. Logarithmic function
3. power function
4. Exponential function
5. Reciprocal function
Solution: Scatter Plot (semi log axis)
Checking for Exponential function
Solution: Scatter Plot (linear axes)
Checking for reciprocal function
Solution: selected plot:
Function chosen: Exponential function

t=0:0.5:5;
w=[6 4.83 3.7 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64];
p=polyfit(t,log(w),1);
m=p(1)
b=exp(p(2))
tp=0:0.1:5;
wp=b*exp(m*tp);
plot(t,w,'o',tp,wp)
xlabel('t'), ylabel('w')
Solution: selected plot:
Function chosen: Exponential function
The boiling temperature of water TB at various altitudes h is given in the following table.
Determine a linear equation in the form TB = mh + b that best fits the data. Use the equation for
calculating the boiling temperature at 5,000 m. Make a plot of the points and the equation.
1- Write a user-defined function that multiplies two polynomials. Name the function
p=polymult(p1, p2). The two input arguments p1 and p2 are vectors of the coefficients of the
two polynomials. The output argument p is the resulting polynomial.
Use the function to multiply the following polynomials:

Check the answer with MATLAB’s built-in function conv.

Solution

Function script
function p = polymult(p1,p2)

na=length(p1); nb=length(p2);
if nb > na
d=p1; p1=p2;
clear b
p2=d;
nd=na; na=nb; nb=nd;
end
for k=1:nb
p(k)=0;
for i=1:k
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
for k=nb+1:na
p(k)=0;
for i=k-nb+1:k
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
for k=na+1:na+nb-1
p(k)=0;
for i=k-nb+1:na
p(k)=p(k)+p1(i)*p2(k+1-i);
end
end
SYMBOLIC MATH

Bushra Fatima
NED University of Engineering & Technology
Aug 10, 2020
Outline

• Numerical vs. Symbolic Operations

• Create symbolic variables/objects

• Create symbolic expressions

Textbook: A. Gilat, Matlab: An Introduction with Applications 6th Edition. John Wiley
& Sons, Incorporated, 2016. (Chapter 11: Symbolic Math)
Numerical VS Symbolic Operations
• When a numerical expression is executed by MATLAB, the
outcome is also numerical.
• exact number [e.g. 1/4 gives 0.2500]
• or a floating point–approximated [e.g. 1/3 gives
0.3333—an approximated value]
• Symbolic operations, which are mathematical operations
with expressions that contain symbolic variables (variables
that don’t have specific numerical values when the
operation is executed). The result of such operations is
also a mathematical expression in terms of the symbolic
variables.
symbolic objects
• A symbolic object can be
• a variable (without a preassigned numerical value),
• a number,
• or an expression made of symbolic variables and
numbers.
• A symbolic expression is a mathematical expression
containing one or more symbolic objects.
• When typed, a symbolic expression may look like a
standard numerical expression.
• However, because the expression contains symbolic
objects, it is executed by MATLAB symbolically.
Step one: Create symbolic objects
String as a single letter or combination of letters with no spaces
symbolic object as a number
Creating several symbolic objects in one command
Creating symbolic expressions
Difference b/w exact and approximate solutions
Difference b/w exact and approximate solutions
Expand command
Expand command
factor command
simplify command
simplify command
Solving algebraic equations
Solving algebraic equations
Problem: Intersection of a circle and a line
Differentiation
Differentiation
Integration
Integration
Integration
Ordinary Differential Equations
Ordinary Differential Equations
Ordinary Differential Equations
Ordinary Differential Equations
Sample problem
Plot the function:
3
𝑦 = 3𝑥 − 26𝑥 + 10
and its first and second
derivatives,
for −2 ≤ 𝑥 ≤ 4 all in the
same plot.

You might also like