0% found this document useful (0 votes)
5 views49 pages

L4 Matricies Operations

Uploaded by

turkisaad65
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)
5 views49 pages

L4 Matricies Operations

Uploaded by

turkisaad65
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/ 49

Array and Matrix

Operations

Lecture notes, based on “Introduction to MATLAB for


Engineers”, William Palm, 3rd edition, and other
textbooks & resources

EE 201
9/24/2024 C4 OE 1
MATLAB has two forms of arithmetic
operations on arrays:

1- array operations, which are also called


element-by-element

2- matrix operations.

9/24/2024 C4 OE 2
Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
(ctranspose)
.’ transpose (transpose)
9/24/2024 C4 OE 3
Matrices Operations

Given A and
B:

Addition Subtraction Product Transpose

9/24/2024 C4 OE 4
Element-by-element (.) operations :

Symbol Operations From Example


+ Scalar-array A+b [6 , 3] + 2 = [8 , 5]
addition
- Scalar-array A–b [8 , 3] – 5 = [3 , -2]
subtraction
+ Array addition A+B [6 , 5] + [4 , 8] = [10 ,13]

- Array A-B [6 , 5] - [4 , 8] = [2 , -3]


subtraction
.* Array A .* B [3 , 5] .* [4 , 8] = [12 , 40]
multiplication
./ Array right A ./ B [2 , 5] ./ [4 , 8] = [2/4 , 5/8]
division
.^ Array A .^ 2 .^ [3 , 5] = [2^3 , 2^5]
exponentiation B [3 , 5] .^ [2 , 4] = [3^2 , 5^4]

9/24/2024 C4 OE 5
- complex conjugate transpose (ctranspose)

A=[3+4i 3-5i 6-8i] then


A=[3+4i 3-5i 6-8i]’

Answer:
A=
3.0000 -4.0000i
3.0000 + 5.0000i
6.0000 + 8.0000i
- Transpose:
A=[3+4i 3-5i 6-8i] then
A=[3+4i 3-5i 6-8i].’
A=
3.0000 + 4.0000i
3.0000 -5.0000i
6.0000 -8.0000i

9/24/2024 C4 OE 6
Operators (Element by
Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power

9/24/2024 C4 OE 7
Element-by-element multiplication(.*)
is defined only for arrays having the same size. The
definition of the product x.*y, where x and y each have n
elements, is
x.*y = [x(1)y(1), x(2)y(2), ..., x(n)y(n)]
if x and y are row vectors. For example, if
x = [2, 4, - 5]; y = [- 7, 3, - 8];

>>z = x.*y gives:


ans =
-14, 12, 40

z = [2(- 7), 4 (3), -5(-8)] = [-14, 12, 40]


9/24/2024 C4 OE 8
Question: What is the result of the following MATLAB code snippet?

A = [1 2 3; 4 5 6; 7 8 9];
B = [9 8 7; 6 5 4; 3 2 1];
F = A .* B;

A) F = [9 8 7; 24 25 24; 21 16 9]

B) F = [1 4 9; 16 25 36; 49 64 81]

C) F = [9 16 21; 24 25 24; 21 16 9]

D) F = [1 2 3; 4 5 6; 7 8 9]

Answer:
C) F = [9 16 21; 24 25 24; 21 16 9]

9/24/2024 C3 OE 9
The built-in MATLAB functions such as :
sqrt(x) and exp(x) automatically operate on array arguments to
produce an array result the same size as the array argument x.

For example, in the following session the result y has the same size as the
argument x.

Thus these functions are said to be vectorized functions.

>>x = [4, 16, 25];


>>y = sqrt(x)
y =
2 4 5
9/24/2024 C4 OE 10
However, when multiplying or dividing
these functions, or when raising them to
a power, you must use element-by-element (.)
operations if the arguments are arrays.
For example, to compute:

y
z = (e sin x) cos2x,
you must type ?
z = exp(y).*sin(x).*(cos(x)).^2
You will get an error message if the size of x is not the
same as the size of y.
The result z will have the same size as x and y.

9/24/2024 C4 OE 11
Array Division (./)
The definition of array division is similar to the definition of array
multiplication except that the elements of one array are divided
by the elements of the other array. Both arrays must have the
same size. The symbol for array right division is (./).

For example, if
x = [8, 12, 15] y = [-2, 6, 5]
Then

>>z = x./y
Gives z = [8/(-2), 12/6, 15/5] = [-4, 2, 3]

9/24/2024 C4 OE 12
Also, if

-4 5 24 20
A= B=
-3 2 –9 4

Then
>>C = A.\B
gives
24/(-4) 20/5 = -6 4
C = -9/-3 4/2 3 2

9/24/2024 C4 OE 13
Matrix-Matrix Multiplication (*)
In the product of two matrices AB, the number of
columns in A must equal the number of rows in B.
The row-column multiplications form column vectors, and these
column vectors form the matrix result. The product AB has the
same number of rows as A and the same number of columns as
B. For example:

6 -2 9 8 (6)(9) + (- 2)(- 5) (6) (8) + (- 2)(12)


10 3 –5 12 = (10)(9) + (3)(- 5) (10)(8) + (3) (12)
4 7 (4)(9) + (7)(- 5) (4) (8) + (7) (12)

64 24
= 75 116
1 116

9/24/2024 C4 OE 14
Use the operator ( * ) to perform matrix
multiplication in MATLAB. The following MATLAB
commands show how to perform the matrix

>>A = [6,-2;10,3;4,7];
>>B = [9,8;-5,12];
>>A*B
ans =
64 24
75 116
1 116

9/24/2024 C4 OE 15
Application
Table shows the hourly cost of four types of manufacturing
processes. It also shows the number of hours required of each
process to produce three different products. Write a MATLAB
program to solve the following:

Hours required to produce one unit


Process Hourly Product 1 Product 2 Product 3
cost($)
Lathe 10 6 5 4
Grinding 12 2 3 1
Milling 14 3 2 5
Welding 9 4 0 3
9/24/2024 16

C4 OE
a- Determine the cost of each process to produce one
unit of product 1?

b- Determine the cost to make one unit of each


product?

c -Suppose we produce 10 units of product 1, 5 units


of product 2, and 7 units of product 3,
compute the total cost?

9/24/2024 C4 OE 17
a- Determine the cost of each process to produce one
unit of product 1?

Hours required to produce one unit


Process Hourly Product 1 Product 2 Product 3
cost($)
Lathe 10 6 5 4
*
Grinding 12 * 2 3 1
Milling 14 * 3 2 5
Welding 9 * 4 0 3

The cost of each process:


60
24
42
36
9/24/2024 18

C4 OE
b- Determine the cost to make one unit of each
product?
Hours required to produce one unit
Process Hourly Product 1 Product 2 Product 3
cost($)
Lathe 10 ’ 6 5 4
Grinding 12 2 3 1
Milling 14 3 2 5
Welding 9 4 0 3
The cost to make one unit of each product
6 5 4
2 3 1
10 12 14 9 * = 162 114 149
3 2 5
4 0 3
1x 4 1x 3
4x 3

9/24/2024 19

C4 OE
c -The total cost to produce 10 units of product 1, 5 units
of product 2, and 7 units of product 3 is:
Hours required to produce one unit
Process Hourly Product 1 Product 2 Product 3
cost($)
Lathe 10 6 5 4
Grinding 12 2 3 1
Milling 14 3 2 5
Welding 9 4 0 3

Product 1 Product 2 Product 3


# of products vector
10 5 7

The total cost = # of products vector * (The cost to make one unit of each product)’

10 5 7 * O/P from
162 114Step b
149 ’ = 3233

9/24/2024 20

C4 OE
Solution
:

9/24/2024 C4 OE 21
9/24/2024 C4 OE 22
Application

The potential energy stored in a spring is kx2/2, where k is the


spring constant and x is the compression in the spring. The force
required to compress the spring is kx.
The following table gives the data for five springs ;

Write a MATLAB program to find the compression x in each spring


and the potential energy stored in each spring.

Spring 1 2 3 4 5
Force (N) 11 7 8 10 9
Spring constant k 1000 800 900 1200 700
(N/m)

9/24/2024 C4 OE 23
% Write your comments
F = [ 11 7 8 10 9 ];
K = [ 1000 800 900 1200 700 ];
% comments
X = F./ K ;
% comments
PT = K .* (X.^2 )/2;
% comments
disp( ' The Compression X = ' );
disp ( X);
disp( ' The potential energy PT = ' );
disp(PT);

9/24/2024 C4 OE 24
Relational and Logical Operators

9/24/2024 C4 OE 25
Relational and Logical Operators
 Character Array and String Array.
 Relational Operators
 Logical Operators
 Truth table
 Order of precedence for operator types
 Logical Array
 Accessing arrays using logical arrays
 Logical Operators & and the find
Function
9/24/2024 C4 OE 26
Character Array
➢A character array is a variable that contains characters.
➢character array are useful for creating input prompts and messages and
for storing and operating on data such as names and addresses.
➢To create a character array variable, enclose the
characters in single quotes (’ ’).
➢For example, the string >>n= ‘Omar Ahmad’
variable n is created as follows: n=
Omar Ahmad
➢The following string, number, is not the same as the
variable number created by typing number = 123.
>>number = ‘123’
number =
123 (continued …)
9/24/2024 C4 OE 27
Character Array
➢-Strings are stored as row vectors in which each column represents a character .

➢For example: The variable n has 1 row and 10 column (each blank space
occupies one column). Thus:
>> size(n)
ans= >>n(6)
1 10 ans=
A
>>first_name=n(1:4)
➢It can be accessed as follows:
first_name=
Omar
>> full_name=[n(1:4),’ S . ‘,n(6:10)]
full_name =
Omar S. Ahmad

9/24/2024 C4 OE 28
Two representations for text
Character Array String Array/Object

Defined using single quotes Defined using double quotes “Hello”


‘Hello’
• Heavier on your system.
• Lighter on your system.
• Normal vector and matrix
• Normal vector and matrix operations do not apply. The
operations apply. string is treated as a single
element even if its length was
• Does not have support for 100.
special string
manipulation. • Supports easier text manipulation
(Finding concatenation,
splitting…etc.)
Both can be called string which can be confusing !
So let’s agree to call it by their specific names; character array, and string
array
9/24/2024 C4 OE 29
String concatenation
Character Array String Array/Object

• Uses normal vector/matrix • Uses the + operator to join


concatenation different strings

• name=‘Omar’ • name=“Omar”
disp(“Hello Mr.” + name)
disp([‘Hello Mr.’ name ])
• Uses the string function to convert
• Need to explicitly convert any a number to a string. However, this
number to string using the is done implicitly when adding a
num2str function before string object to a number.
concatenation.
• r=5
• r=5 disp(“Radius = “ + string(r))
or
disp([‘Radius = ‘ num2str(r)])
• disp(“Radius = “ + r)

9/24/2024 C4 OE 30
Length of a String
Character Array String Array/Object

• Uses normal vector/matrix • Uses the strlength function


length function
• msg=“Hello”
• msg=‘Hello’ x=length(msg)
x=length(msg)
• x will have the number 1 stored.
• x will have the number 5 stored Why? because msg has 1 string
object stored.
• msg=‘Hello’ • msg=“Hello”
x=strlength(msg) x=strlength(msg)

• x will have the number 5 stored • x will have the number 5 stored
as well so strlength also works
with character arrays

9/24/2024 C4 OE 31
String comparison
Character Array String Array/Object

• Uses special strcmp function • Can use the strcmp function but
more easily, uses the == operator

• name1=‘Hamza’ • name1=‘Hamza’
name2=‘Hamid’ name2=‘Hamid’
x=strcmp(name1,name2) x= name1==name2

• x will have logical 0 (False) • x will have logical 0 (False)


because name1 is not the because name1 is not the same as
same as name2 name2

9/24/2024 C4 OE 32
Converting between types
Character Array to String Array String Array to Character Array
string(‘Hello’) char(“Hello”)

Character Array to Number String Array to Number


str2num(‘5.32’) str2num(“5.32”)
str2num(‘-213’) str2num(“-213”)

Number to Character Array Number to String Array


num2str(5.32) string(5.32)
num2str(-213) string(-213)

9/24/2024 C4 OE 33
Relational Operators

Mathematical MATLAB Meaning


< < Less than
≤ <= Less than or equal to
> > greater than
≥ >= greater than or equal to
= == equal to
≠ ~= not equal to

9/24/2024 C4 OE 34
Examples of Relational Operators

Logical Array

Logical Array

Logical Array

Logical Array (continued …)


9/24/2024 C4 OE 35
Examples of Relational Operators

Remember
>> [y1,y2]=find(x)
masking
y1 =
x with
1 3
(x~=0)
y2 =
-2 4

Note: the difference between the result obtained by


x (x~=0) and the result obtained by find(x).

(continued …)
9/24/2024 C4 OE 36
Examples of Relational Operators

Suppose x=[ 6 , 3 , 9 , 11]


y=[14 , 2 , 9 , 13]

Use MATLAB to find the values


and indices of the elements in x
that are less than the
corresponding elements
in y.

9/24/2024 C4 OE
37
.
Logical Operators

Operator Name Definition


~A returns an array the same dimension as A; the new
~ NOT array has ones where A is zero and zeros where A is
non zero.
A & B returns an array the same dimension as A and B;
& AND the new array has ones where both A and B have
nonzero elements and zeros where either A or B is zero
A|B returns an array the same dimension as A and B;
the new array has ones where at least one element in A
| OR
or B is nonzero and zeros where A
B are both zero.
(continued …)
9/24/2024 C4 OE 38
.
Logical Operators

Operator Name Definition

Operator for scalar logical expressions


Short-Circuit A && B
&&
AND returns true if both A and B evaluate to true, and false if
they do not.
Operator for scalar logical expressions
Short-Circuit A || B
||
OR returns true if either A or B or both evaluate to true and
false if they do not
b=1; a=20; x=(b~=0) && (a/b > 18.5) b=1; a=20; x=(b~=0) || (a/b > 18.5)
X= 1 X= 1
(short circuiting)

b=0; a=20; x=(b~=0) && (a/b > 18.5) b=0; a=20; x=(b~=0) || (a/b > 18.5)
X= 0 X= 1
(short circuiting)

9/24/2024 C4 OE 39
Truth table

x y ~x x|y x&y
True(1) True(1) False(0) True(1) True(1)

True(1) False(0) False(0) True(1) False(0)

False(0) True(1) True(1) True(1) False(0)

False(0) False(0) True(1) False(0) False(0)

x y ~x x|y x&y
1 1 0 1 1
1 0 0 1 0
0 1 1 1 0
0 0 1 0 0
9/24/2024 C4 OE 40
Order of precedence for operator types:
1. Parentheses (), 6. Colon operator (:)

2. Transpose (.'), power (.^), complex 7. Less than (<), less than or equal to
conjugate transpose ('), matrix (<=), greater than (>), greater than
power (^) or equal to (>=), equal to (==), not
equal to (~=)
3. Unary plus (+), unary minus (-),
logical negation (Tilde ~)
8. Element-wise logical AND (&)
4. Multiplication (.*), right division
(./), left division (.\), matrix 9. Element-wise logical OR (|)
multiplication (*), matrix right
division (/), matrix left division (\) 10. Short-circuit logical AND (&&)

5. Addition (+), subtraction (-) 11. Short-circuit logical OR (||)


9/24/2024 C4 OE 41
Example - 01

Assume the variables x=5, y=6, and z=8. Indicate if each of


the following conditions is true or false:

a) x==5 || y>3 →→ T

b) 2~=y && z==4 →→ F

c) 2~=y || z==4 →→ T (short circuiting)

9/24/2024 C4 OE 42
Example - 02

x=[2, 4,0];y=[-2,0,5]; z=[1 1 1]; what are the results of the


following expressions?

a) z | x & y | ~z

~z → x & y → z | x & y → z | x&y|~z


0 0 0 1 0 0 1 1 1 1 1 1
Ans=
b) x >= z & ~y < z 1 1 1
~y → x >=z → ~y < z → x >= z & ~y < z
0 1 0 1 1 0 1 0 1 1 0 0
Ans=
1 0 0
9/24/2024 C4 OE 43
Example - 03

Construct a logical expression to represent each of the following


conditions:
a. score is greater than or equal to 80 but less than 90
Another
80<=score && score<90 solution
score>=80 && score<90

b. N is between 0 and 7
Another
0<N && N<7 solution
N>0 && N<7

c. M is between -3 and 4 but not equal to 0


-3 < M && M < 4 && M~=0
9/24/2024 C4 OE 44
Logical Array

Logical arrays can be created with :

❖The relational operators


❖Logical operators
❖Logical function

(continued …)
9/24/2024 C4 OE 45
Logical Array

➢Logical arrays may have only the values 1(true) and 0 (false)
➢It is not necessarily any array contains only 0s and 1s a logical array. For example:

>>x = [-2:2]
x=
-2 -1 0 1 2
>>w=[1,0,0,0,1];
>>k = (abs(x)>1)
k= >>v=x(w)
1 0 0 0 1 ??? Subscript indices must either be real
>>z = x(k)
z= positive integers or logical.
-2 2
k and w appear the same; but k is logical array and w is a numeric array.

9/24/2024 C4 OE 46
Logical function

➢-Logical function returns an array that can be used for logical indexing and

logical tests.

➢-So to correct the error in the previous example, you may type instead

w=logical([1,0,0,0,1]) before typing v=x(w).

9/24/2024 C4 OE 47
Accessing arrays using logical arrays

➢When a logical array is used to address another array , it extracts from that
array the elements in the locations where the logical array has 1s.
➢ For example: How to extract the diagonal elements of any array ?
>>A=[ 5 , 6 , 7 ; 8 , 9 , 10 ; 11 , 12 , 13 ];
(1) (2)
1 0 0
>>C=A([1,5,9]) 5 6 7
0 1 0 >>B=logical(eye(3))
0 0 1 OR C= 10
8 9

>>C=A(B) 5 9 13 11 12 13

5 6 7
C=
8 9 10
11 12 13 5 9 13
9/24/2024 C4 OE 48
Logical Operators & and the find Function

>>x = [5, -3, 0, 0, 8]; >>values = y(x&y)


>>y = [2, 4, 0, 5, 7]; values =
2 4 7
>>z = find(x&y)
>>how_many = length(values)
z=
how_many =
1 2 5
3

Note : The find function Note : The difference between the


returns the indices, and not result obtained by y(x&y) and the
the values. result obtained by find(x&y).

9/24/2024 C4 OE 49

You might also like