Matlab for Engineers Manipulating Matlab Matrices Chapter 4.
Lecture 2 - Matlab Building Blocks - Arrays and Matrices
-
Upload
mostafa-ahmadi -
Category
Documents
-
view
236 -
download
4
description
Transcript of Lecture 2 - Matlab Building Blocks - Arrays and Matrices
Eran Eden, Weizmann 2008 © 1
Introduction to Matlab & Data Analysis
Topic #2 (continued): The Matlab Building Blocks –
Arrays and Matrices
Announcements Apostrophe or Single quotes ‘ ‘
Parenthesis ()
HW Lab assistance:
2
3
Previously…
Matlab is a high level language Easy to learn
Easy to debug
Easy visualization
Many useful “toolboxes”
The Matlab working environment Our first program
help!
Variables… example:
count = 5;
4
Variables
Tip #1: Give your variable meaningful names.
salary = 9000;
hours = 5;
And NOT…
a = 9000;
b = 5;
5
Variables
Tip #2: Don’t make variable names too long
salary_I_got_for_my_work_at_the_gasoline_station = 9000;
salary_I_got_for_my_work_in_the_bakery = salary_I_got_for_my_work_at_the_gasoline_station * 3;
disp(salary_I_got_for_my_work_in_the_bakery);
Very bad choice of variable name!!!
Tip #3: Whatever you do - be consistent.
6
Variables
Several functions in a row. Should be separated by a comma
But:
7
Today on the menu
Operations on variables
1D Arrays
Creating
Indexing
Operating on
2D Arrays (matrices)
3D Arrays
Operations on variables
8
Round up
>> x = 2.2;
>> ceil(x)
ans =
3
Round down
>> x = 2.6;
>> floor(x)
ans =
2
Round
>> x = 2.6;
>> round(x)
ans =
3
>> x = 2.2;
>> round(x)
ans =
2
>> x = 1.5;
>> round(x)
ans =
2
Operations on variables I want to get the absolute value of a variable but don’t know
the command… what should I do?
… Google it!
9
Absolute value of a number
>> x = -2
>> abs(x)
ans =
2
10
Data is stored in data structures
A Data Structure is a set of values that are organized in a predefined manner
Examples:
Tree (parent)
Stack (LIFO)
Queue (FIFO)
Array (index)
And more…
11
Array is the main data structure used in Matlab
Almost everything we build in Matlab - we build from arrays.
The variables that contain one element that we learned so far can be thought of as a degenerate case of a 1 x 1 array.
12
Examples of 1D and 2D arrays An 1D array containing student grades
An 1D array containing protein levels
An 1D array of characters
A 2D array, also called matrix, of distances between cities
Note that all the elements within an array are of the same variable type
100 100 100 98 100 50 99
0.54 0.01 0.0 1.2 1.24
0 23 120 21
23 0 56 10
120 56 0 8
D o n ‘ t w o r r y , b e h a p p y
13
Creating 1D Arrays
The simplest way to create an array
>> x = [1 2 3 8 12 40];
>> disp(x)
1 2 3 8 12 40
Adding commas to separate the numbers gives the same result:
>> x = [1, 2, 3, 8, 12, 40];
>> disp(x)
1 2 3 8 12 40
No problem! This is how you do it: >>x = [ 10 11 12 13 14 15 16 ... 17 18 19 20 21 22 23 24 25 ... 26 27 28 29 30 31 32 33 34 ... 35 36 37 38 39 40 41 42 43 ... 44 45 46 47 48 49 50 51 52 ... 53 54 55 56 57 58 59 60 61 ... 62 63 64 65 66 67 68 69 70 ... 71 72 73 74 75 76 77 78 79 ... 80 81 82 83 84 85 86 87 88 ... 89 90 91 92 93 94 95 96 97 ... 98 99 100];
14
Creating 1D Arrays
How do we create an array containing all the numbers between 10 and 100 ?
15
Creating 1D Arrays
Alternatively we can do this:
>>x = 10 : 1 : 100;
>> disp(x) Columns 1 through 19
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
Columns 20 through 38
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
Columns 39 through 57
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
Columns 58 through 76
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
Columns 77 through 91
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Start at 10 Stop when you get to 100
count up by 1
16
Creating 1D Arrays
What is the value of x?
>> x = 0 : 0.1 : 2;
>> disp(x)
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9
1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9
2
How can you create an array with numbers from 100 to 1 in decreasing order?
17
Creating 1D Arrays
Initializing a vector to zeros >> x = zeros(1, 5)
x =
0 0 0 0 0
Initializing a vector to ones >> x = ones(1, 6)
x =
1 1 1 1 1 1
Initializing a vector to random numbers >> x = rand(1, 4)
x =
0.9501 0.2311 0.6068 0.4860
Generates a Uniformly distributed pseudo-random number between 0 and 1
1 row, 6 columns
18
Concatenating 1D Arrays
Example:
x = 1 : 5;
y = 100 : 105;
z = [x, y, x];
disp(z);
1 2 3 4 5 100 101 102 103 104 105 1 2 3 4 5
x y x
x, y and x are concatenated into one array
19
Indexing 1D Arrays Question: How do we retrieve/manipulate the content
of a specific element inside an array?
Answer: We use a mailbox like system called indexing
x(i) is the i’th element of x
1 2 3 4 5
20
Indexing 1D Arrays We will study different types of indexing through
examples: What is the output of the following program?
x = 10 : -1 : 1;
y = x(3);
disp(y);
8
What is the output of the following program?
x = 10 : -2 : 1;
y = x(5);
disp(y);
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
8
x
y
21
Indexing 1D Arrays
What is the output of the following program?
x = 10 : -1 : 1;
y = x(12);
disp(y);
What is the output of the following program?
x = 10 : -1 : 1;
y = x(3.2);
disp(y);
??? Index exceeds matrix dimensions.
??? Subscript indices must either be real positive integers or logicals.
22
Indexing 1D Arrays
We can retrieve more than one element at a time: What is the output of the following program?
x = 10 : -1 : 1;
y = x([3,9,4]);
disp(y);
What is the output of the following program?
x = 10 : -1 : 1;
y = x(2 : 2 : 8);
disp(y);
23
Indexing 1D Arrays
Indexing the last element in a vector...
What is the output of the following program? x = 10 : -1 : 1;
y = x(end)
disp(y);
1
What is the output of the following program?
x = 10 : -1 : 1;
z = x(end - 1)
disp(z);
2
24
Indexing 1D Arrays
The same indexing can be applied to arrays of chars.
What is the output of the following program?
str = 'If I was a rich man, Yaba dibi dibi ... dibi dibi di';
str2 = str([1 : 10, 21: 25]);
disp(str2);
If I was a Yaba
25
Using indexing to edit 1D arrays
We can manipulate the content of an array
What is the output of the following program?
x = 10 : -1 : 1;
x(2) = 10;
disp(x);
What is the output of the following program?
x = 10 : -1 : 1;
x(14) = 99;
disp(x);
10 9 8 7 6 5 4 3 2 1
10 10 8 7 6 5 4 3 2 1
Remark: Notice that adding an element beyond the array boundary is NOT an error!
10 9 8 7 6 5 4 3 2 1 0 0 0 99
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
11 12 13 14
26
Using indexing to edit 1D arrays
We can erase parts of an array
What is the output of the following program?
x = 10 : -1 : 1;
x(2) = [];
disp(x);
What is the output of the following program?
x = 10 : -1 : 1;
x(2 : 4) = [];
disp(x);
10 9 8 7 6 5 4 3 2 1
10 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7
27
1D Array Orientation
So far we’ve seen row vectors (one row and multiple columns), How can one create a column vector (one column and multiple rows) ?
Use semicolon seperator:
x = [1; 2; 3; 4; 5];
disp(x);
1
2
3
4
5
Use transpose operator x = [1, 2, 3, 4, 5]; y = x'; disp(y)
1 2 3 4 5
Simple operations on 1D arrays
What is the output of the following program?
>> c = 1 : 0.1 : 2
>> round(c)
ans =
1 1 1 1 1 2 2 2 2 2 2
What is the output of the following program?
>> c = 1 : 0.1 : 2
>> ceil(c)
1 2 2 2 2 2 2 2 2 2
What is the output of the following program?
>>abs(floor(-0.3 : 0.1 : 0.3))
28
All the operations that were applied on variables containing one element can be applied to 1D arrays
Simple operations on 1D arrays
1 1 1 0 0 0 0
29
30
Simple operations on 1D arrays
Finding the maximal number in a vector
>> x = 1 : 50;
>> max(x)
50
Finding the minimal number in a vector
>> min(x)
1
Finding the mean of a vector
>> mean(x)
25.500
Finding the standard diviation of a vector
>> std(x)
14.5774
31
Simple operations on 1D arrays
Finding the size of a vector
>> x = 1 : 50;
>> size(x)
ans =
1 50
>> y = x'
>> size(y)
ans =
50 1
What is length then?
max(size(x))
Finding the length of a matrix
>> x = 1 : 50;
>> length(x)
ans =
50
>> y = x'
>> length(y)
ans =
50
Returns the maximal dimension
32
Simple operations on 1D arrays
x= 1 : 50
What is the difference between:
y = x(length(x));
and
y = x(end);
“Same same…”
33
Simple operations on 1D arrays
The rand(m,n) function is a pseudo randon number generator. The
function starts from a number (seed) which is operated on in a
complicated non linear formula. Each pass produces a number
that is apperantly uncorrelated to the previous number or to the
following number. It is “pseudo” in the sense that if we start
from the same seed we will always get the same series of
numbers (deteministic). However, it is random enough for the
purpose of simulations. In the Matlab environement the seed
changes as well in the default settings.
A period is the number of passes between two identical numbers,
in which the numbers do not repeat. The period is usually set to
be extermely long. (Wikipedia).
34
Sub-array searching
The “find” operation returns indices
>> x = [2 8 7 6 4 2 3];
>> find(x == 2)
1 6
>> find(x > 3)
2 3 4 5
How do we get the values in x that are larger than 3?
How do we get the values in x that are larger than 3 that is most to the right?
Finds indices of all values equal to 2
Finds indices of all values larger than 3
35
Sub-array searching
The “find” operation How do we get the values in x that are larger than 3? >>y=x(find(x>3))
y =
8 7 6 4
How do we get the values in x that are larger than 3 that is most to the right?
>>v=x(max(find(x>3)))
v =
4
More functions on vectors
Intersection of two vectors >> doron_free_days = 1 : 2 : 31;
>> tal_free_days = [ 6 7 8 12 14 18 19 20];
>> meeting_days = intersect(doron_free_days, tal_free_days)
meeting_days =
7 19
Union of two vectors >> dog_eating_days = union(doron_free_days, tal_free_days)
dog_eating_days =
1 3 5 6 7 8 9 11 12 13 14 15
2 17 18 19 20 21 23 25 27 29 31
36
37
Arithmetic operations on 1D arrays
The plus (+) and minus (-) operations are naturaly extended to arrays
Example 1:
x =[ 2 4 6];
y = x – 1
y =
1 3 5
Example 2:
x = x + x
x =
4 8 12
Notice that the operation is applied to all the elements in the array
(1) Scalar multiplication
price = [10 20 30];
new_price = price * 2
new_price =
20 40 60
You can use paranthesis to change order of multiplication (just like in regular math) >> (price + 1) * 2
ans =
22 42 62
>> price + 1 * 2
ans =
12 22 32
38
Arithmetic operations on 1D arrays
The multiplication * is a bit more tricky...
(2) Vector multiplication
price = [10 20 30];
quantity = [3 2 1]';
price * quantity
ans =
100
Vector dimensions should match (exactly like in mathemtics)
39
Arithmetic operations on 1D arrays
3
2
1
10 20 30
price
quantity'
The multiplication * is a bit more tricky...
price = [10 20 30];
quantity = [3 2 1];
price * quantity
??? Error using ==> mtimes
Inner matrix dimensions must agree.
10 20 30
price quantity
3 2 1 *
*
(3) Element by element multiplication
>> price = [10 20 30];
quantity = [3 2 1];
price .* quantity
ans =
30 40 30
40
Arithmetic operations on 1D arrays
10 20 30
price
The multiplication * is a bit more tricky...
quantity 3 2 1 .*
Summary Example of 1D arrays: The Casino Fraud...
Simulate the throw of two dice (i.e. randomly choose two numbers between 1 and 6)
>> dice = ceil(6 * rand(1,2))
dice =
6 5
Create loaded two dice where the chances of getting a 6 is ½ and the chances of getting the other numbers is 1/10 for each number.
>> dice = ceil(10 * rand(1,2));
>> dice(find(dice > 6)) = 6
dice =
6 6
41
Summary Example of 1D arrays: A small warm-up on plotting arrays...
What will the following program plot?
x = 0 : 0.1 : 2;
x = x * pi;
y = sin(x);
plot(x, y);
Radians or degrees?
42
0 1 2 3 4 5 6 7-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Matrices (2D arrays)
43
44
Matrices (2D arrays)
Why do we need Matrices?
1D Arrays that we learned so far can be thought of as a degenerate case of a 1 x N or N x 1 2D array.
10 21 10 21
73 21 18 21
10 4 8 21
3 21 10 45
8 21 2 21
Employee Salary Vacation days
Sickness days
Yosi 10000 18 4
Dudu 12000 8 10
Ruti 30000 10 12
Pinhas 60000 2 1
45
Creating matrices
One way to create a matrix:
x = [1 2 3 4
5 6 7 8]
x =
1 2 3 4
5 6 7 8
Another way:
x = [1 2 3 4; 5 6 7 8]
x =
1 2 3 4
5 6 7 8
46
Creating Matrices x = ones(3,4)
x = 1 1 1 1 1 1 1 1 1 1 1 1
x = zeros(3,4)
x = 0 0 0 0 0 0 0 0 0 0 0 0
Number of rows
Number of columns
open inetrval does not include ends
47
Creating Matrices Initiating a matrix with random values: x = rand(3,4)
x =
0.0832 0.0018 0.0143 0.6034
0.0539 0.8238 0.3402 0.2905
0.4206 0.8405 0.6103 0.3517
Simulate a random choice of numbers in a roulette game (0, 00, 1...36). ’00’ should be represented by -1. Store result s in a 3 by 3 matrix.
x = ceil(rand(3,3)* 38) – 2
x =
13 15 29
25 25 35
19 22 18
48
Indexing 2D arrays
Indexing 2D arrays is done the similarly to 1D arrays
x(h,w) is the h row and the w column
what is the value of x(3,4)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
3
4
what is the value of x(1 : 3, 4)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
3
4
2 1
what is the value of x(2 : 3, 3 : 4)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
49
Indexing 2D arrays
x(h,:) is the h row x(:,w) is the w column
what is the value of x(3,:)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
what is the value of x(:, 1:2)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
what is the value of x(:, :)?
10 21 10 4
73 21 18 10
10 4 8 21
3 21 10 45
8 21 2 21
50
Indexing 2D arrays
>> a = [1 2 3; 4 5 6; 7 8 9];
>> disp(a)
1 2 3
4 5 6
7 8 9
>> a(1)
ans =
1
>> a(2)
ans =
4
>> a(3)
ans =
7
It’s possible to index a 2D array using a single coordinate
>> a(5)
ans =
5
>> a(6)
ans =
8
>> a' ans = 1 4 7 2 5 8 3 6 9
This is the order matlab reads matrix elements
51
Using indexing to edit 2D arrays
y = zeros(3,3);
y(1,3) = 4
y =
0 0 4
0 0 0
0 0 0
What does the matrix y look like?
The matrix size on the left and right of the assignment should match in size.
y = zeros(3,3);
x = ones(2,2);
y(1 : 2, 1 : 2) = x
y =
1 1 0
1 1 0
0 0 0
What does the matrix y look like?
Size 1 x 1 Size 1 x 1
Size 2 x 2 Size 2 x 2 = =
52
Using indexing to edit 2D arrays
y = zeros(3,3);
y(1:2,1:2) = 4
y =
4 4 0
4 4 0
0 0 0
What does the matrix y look like?
The matrix size on the left and right of the assignment should match in size,
unless the right matrix has a size of 1 x 1
Size 2 x 2 Size 1 x 1
53
Using indexing to edit 2D arrays
y = zeros(5,5);
x = ones(2,2);
y = x
y =
1 1
1 1
What does the matrix y look like?
The matrix size on the left and right of the assignment should match in size,
unless the right matrix has a size of 1 x 1 OR
unless you are overwriting a matrix
Size 5 x 5 Size 2 x 2
54
Using indexing to edit 2D arrays
y = zeros(3,3)
y([1, 3] , [1, 3]) = 4
y =
4 0 4
0 0 0
4 0 4
What does the matrix y look like?
y = zeros(3,3);
x = ones(2,2);
y(2 : 3, 2 : 3) = x
y =
0 0 0
0 1 1
0 1 1
What does the matrix y look like?
y = zeros(3,3);
x = ones(4,4);
y(2 : 3, 2 : 3) = x
??? Subscripted assignment dimension mismatch.
What does the matrix y look like?
55
Using indexing to edit 2D arrays
>> y = [1 2 3; 4 5 6; 7 8 9];
>> disp(y)
1 2 3
4 5 6
7 8 9
>> y(2, :) = [];
>> disp(y);
1 2 3
7 8 9
>> y(: , [1 3]) = [];
>> disp(y);
disp(y);
2
8
Erasing a part of a matrix
What does the matrix y look like?
>> y = [1 2 3; 4 5 6; 7 8 9];
>> disp(y)
1 2 3
4 5 6
7 8 9
>> y(2, 2) = []
??? Indexed empty matrix
assignment is not allowed
What does the matrix y look like?
56
Simple operations on 2D arrays
Finding the size of a matrix
x =[ 2 4 6
3 6 9];
size(x)
2 3
Finding the length of a matrix
length(x)
3
Number of rows Number of columns
All the operations that were applied on 1D arrays can be applied to 2D arrays
transpose
x =[ 2 4 6
3 6 9];
x'
2 3
4 6
6 9
57
Simple operations on 2D arrays
Finding the maximal numbers in each matrix column
>> x = [1 2 3
7 8 9
4 5 6];
>> max(x)
ans =
7 8 9
Think of two ways to get the maximal element in the entire matrix…
>>max(max(x))
Finding the mean of each matrix column
>> mean(x)
ans =
4 5 6
How do we get the mean of each matrix row?
>> mean(x,2)
58
Simple operations on 2D arrays
Finding elements within 2D arrays is similar to 1D arrays.
Finding using 2 coordinates indexing:
>> x = [1 2 3
7 8 9
4 5 6];
>> [h, w] = find(x > 5)
h =
2
2
2
3
w =
1
2
3
3
59
Simple operations on 2D arrays
Finding things within 2D arrays is similar to 1D arrays.
Finding using 1 coordinate indexing
>> x = [1 2 3
7 8 9
4 5 6];
>> inds = find(x > 5)
inds =
2
5
8
9
60
Arithmetic operations on 2D arrays
The plus (+) and minus (-) operations are naturaly extended and 2D arrays
Example 1:
x =[ 2 4 6
3 6 9];
y = x – 1
y =
1 3 5
2 5 8
Example 2:
x = x + x
x =
4 8 12
6 12 18
y =
1 3 4
2 4 7
61
Arithmetic operations on 2D arrays
Question: write a commmand that subtracts 1 from all the values in y that are larger than 4 and stores it back into y
y = [1 3 5
2 5 8];
Answer
y(find(y > 4)) = y(find(y > 4)) - 1
(1) Scalar multiplication
price = [10 20 30; 2 3 4];
new_price = price * 2
new_price =
20 40 60
4 6 8
62
Arithmetic operations on 2D arrays
63
Arithmetic operations on 2D arrays
(2) Matrix multiplicaiton
price = [2 3 4; 2 4 5];
quantity = [4 1; 0 2; 2 1];
price * quantity
ans =
16 12
18 15
4 1
0 2
2 1
2 3 4
2 4 5
* = 16 12
18 15
64
Arithmetic operations on 2D arrays
(3) element by element multiplicaiton
price = [2 3 4; 2 4 5];
quantity = [4 0 2; 1 2 1];
price .* quantity
ans =
8 0 8
2 8 5
2 3 4
2 4 5 .* = 4 0 2
1 2 1
8 0 8
2 8 5
65
“Flattening” 2D arrays We can turn a matrix into a vector
(ordered according to columns)
x = [1 2 3
4 5 6
7 8 9];
y= [x(:, 1); x(:, 2); x(:, 3)]
y =
1
4
7
2
5
8
3
6
9
Alternatively the following command will do the trick…
y = x(:)
y =
1
4
7
2
5
8
3
6
9
66
Final small example In the matrix vac_days each column represents the number of vacations days an employee
took in the last 3 months.
In the matrix salaries each column represents that employee’s salary in the last 3 months.
Correct the salaries so that employees that took less then 3 days of vacation in a certain month get a 10% bonus to their salary.
>> vac_days = [1 5 10 0; 0 0 1 10 ; 0 0 5 7 ]
vac_days =
1 5 10 0
0 0 1 10
0 0 5 7
>> salaries = [6000 6000 7000 20000; 6000 6000 7000 20000; 7000 7000 7000 20000;]
salaries =
6000 6000 7000 20000
6000 6000 7000 20000
7000 7000 7000 20000
67
Final small example
Answer:
>> inds = find(vac_days < 3);
>> salaries(inds) = salaries(inds) * 110/100;
>> disp(salaries)
6600 6000 7000 22000
6600 6600 7700 20000
7700 7700 7000 20000
3D arrays…
68
10 21 10 21
73 21 18 21
10 4 8 21
3 21 10 45
8 21 2 21
10 21 10 21
73 21 18 21
10 4 8 21
3 21 10 45
8 21 2 21
10 21 10 21
73 21 18 21
10 4 8 21
3 21 10 45
8 21 2 21
Color images are 3D arrays (We will learn this at the end of the course)
Why the heck do we need 3D arrays ?#@!?
R
G
B
69
3D arrays
All the (initialization / indexing / operations) that we learnt on 2D arrays can be applied to 3D arrays.
In fact, they can be applied to any N dimensional array.
70
3D arrays - example >> x = zeros(3,3,3)
x(:,:,1) =
0 0 0
0 0 0
0 0 0
x(:,:,2) =
0 0 0
0 0 0
0 0 0
x(:,:,3) =
0 0 0
0 0 0
0 0 0
71
3D arrays (example continued)
>> x(:, :, 3) = ones(3,3)
x(:,:,1) =
0 0 0
0 0 0
0 0 0
x(:,:,2) =
0 0 0
0 0 0
0 0 0
x(:,:,3) =
1 1 1
1 1 1
1 1 1
72
3D arrays (example continued) >> x(2, 2, :) = 3
x(:,:,1) =
0 0 0
0 3 0
0 0 0
x(:,:,2) =
0 0 0
0 3 0
0 0 0
x(:,:,3) =
1 1 1
1 3 1
1 1 1
73
Tip of the day… improving your code readbility
Use spaces and tabs to make your code more clear
This code is
Better than this one...
age=10; weight=50; height= 1:0.1:4; hair= 2:0.1:5;
age = 10; weight = 50; height = 1 : 0.1 : 4; hair = 2 : 0.1 : 5;