Sunteți pe pagina 1din 21

# Arrays in Matlab

Why arrays?
Calculate statistics for 100 high temperatures
from the last 100 days.
temp1 = 82
temp2 = 78
...
temp100 = 81
Tedious and error-prone
Need a way to concisely represent related data

Array
Collection of related numbers
Arranged in rows and/or columns
Stored in a single variable
A variable holding a single value, such as
we have seen up until now, is called a
scalar.
value = 5 % value is a scalar

Row Array

## One variable that consists of n elements

Sometimes called a row vector

Example
create a row array called temps that holds high
temps = [82 78 91 87] OR
temps = [82, 78, 91, 87] (commas are optional)

## Creating row arrays

If the elements have a constant spacing,
can use a format similar to the for
command
variable_name = [first : spacing : last] OR
variable_name = first : spacing : last
(brackets are optional)
If spacing is omitted, it is assumed to be 1
variable_name = first : last

Examples
W = [1 : 1 : 5]
W is 1 2 3 4 5
X = 1.5 : 0.1: 2.1
X is 1.5 1.6 1.7 1.8 1.9 2.0 2.1
Y = [10 : -2 : 0]
Y is 10 8 6 4 2 0
Z = -3 : 3
Z is -3 -2 -1 0 +1 +2 +3

## Creating Row Arrays

If the elements have constant spacing, can
also specify the first element, the last
element, and the number of elements
variable_name = linspace (first, last, num)
sample1 = linspace (1, 10, 10)
creates 1 2 3 4 5 6 7 8 9 10
sample2 = linspace (4.2, 10.2, 7)
creates 4.2 5.2 6.2 7.2 8.2 9.2 10.2

## Arrays are very powerful

Ex: Draw a sine wave. Array y will
automatically have as many elements as
array x. plot( ) creates a graph.
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x , y)

Column Arrays
Just like a row array,
it is one variable that
consists of n
elements
Sometimes called a
column vector

## Creating Column Arrays

A = [10.0; 20.1; 30.6; 120.2]
OR
A = [10.0
20.1
30.6
120.2]

## Creating Column Arrays

Can also create column arrays using the
other techniques discussed for row arrays.
Two-step process:
Create a row array
Transpose the array

## Transpose: switch rows to columns or

vice versa
Transpose operator is '

Example
X=1:1:3
Y = X'

X is 1 2 3
Y is 1
2
3

Another Example
X = linspace (1, 5, 3)
Y = X'

X is
1 3 5
Y is
1
3
5

## Yet Another Example

Array creation and transposition can be
combined in one statement
Arr = (1.0 : 0.2 : 1.4)'

Arr is
1.0
1.2
1.4

Subscripts
Individual array elements accessed by
using subscripts
Subscript is the element number
Subscript must be an integer within the
range of the array

Examples

x = temps (1)
y = temps(3)
x = temps (78)
temps(4) = 23

% x is 82
% y is 91
%error - subscript too big
%changes content of last
%element from 87 to 23

More Examples
A = [2; 3; 4] % A is 2
3
4
m = A(1) % m is 2
n = A(3) % n is 4
A(2) = 7 % A now 2
7
4

A = [2; 3; 4]

for k = 1:1:3
A(k) = 0
end

%A is 2
3
4
%A is 0
0
0

## Still More Examples

Can use a colon to represent a range of
subscripts
A = [2 4 6 8 10]
B = A(2:4) % B is 4 6 8
A(3:5) = 0 % A is now 2 4 0 0 0

Array Operations
Two kinds of operations:
Element-by-element, where operations are
performed on each element (next)
Using the rules of linear algebra (later)

Assignment Statements
Contents of one array copied element by
element into another array
Both arrays must be the same size
If new array does not exist, it will be
created to be the same size as the old
array
Ex: X = 1: 4
% X is 1 2 3 4
Y=X
% Y is 1 2 3 4

Scalar - Array
Operations
Apply operation to each element of the
array
X = [1, 2, 3]
Y=X+2
% Y is 3 4 5
Y=X - 1
% Y is 0 1 2
num = 3
Y = X * (num + 1) % Y is 4 8 12
Y=X/2
% Y is 0.5 1 1.5

Example
Plot the equation y = mx + b
x should vary between -10 and +10
m and b should be chosen by the user

Algorithm
Prompt for and read in m (the slope) and b
(the offset)
Create an array X containing values
between -10 and +10
Create array Y using this formula:
Y = m*X + b
plot X vs Y

Example
m = input ('Please enter the slope: ');
b = input ('Please enter the offset: ');
X = [-10 : 10];
Y = (m * X) + b;
plot (X, Y)

12
10
8
6
4
2
0
-2
-4
-6
-8
-10

-8

-6

-4

-2

10

Element-by-Element
Operations
A = B op C means A(1) = B(1) op C(1)
A(2) = B(2) op C(2)
...
A(n) = B(n) op C(n)
- (subtraction)
.* (multiplication)
./ (division)

Examples
A = [ 1 2 3]
B = [ 4 5 6]
C=A+B
C=B -A
C = A .* B
C = B ./ A

% C is 5 7 9
% C is 3 3 3
% C is 4 10 18
% C is 4 2.5 2

Two-Dimensional Arrays
A two dimensional array has rows and
columns, like a table
Sometimes called a matrix

10

Creating Matrices
Similar to creating vectors (onedimensional arrays)
Use commas or spaces to separate
elements in a specific row
Use semicolon or enter to separate
individual rows

Examples
A = [1, 2, 3; 4, 5, 6]

A is

123
456

B = [1 2
34
5 6]

B is

1 2
3 4
5 6

11

Creating Matrices
Can also use
first: spacing: last
first: last (spacing assumed to be 1)
linspace (first, last, number)

More Examples
C = [1:2:7; linspace(1,10,4)]
C is 1 3 5 7
1 4 7 10
D = [0, 0, 3:5
D is 0 0 3 4 5
0, 0, 4:6
00456
0 0 7:9]
00789

Subscripts
Individual array elements accessed by
using subscripts
Subscript is row number, column number
Both parts of the subscript must be
integers within the range of the array

12

Examples
A = [1 1 1; 2 2 2; 3 3 3]
A is 1 1 1
222
333
m = A(1,1)
% m is 1
n = A(3, 1)
% n is 3

Examples, con't
A(2, 2) = 5

A(1, 1:3) = 8

A is 1 1 1
252
333
A is 8 8 8
252
333

Examples (con't)
A(1:3, 2) = 7

A is 8 7 8
272
373

B = [10 10 10]
A (1, :) = B

A is 10 10 10
2 7 2
3 7 3
Colon, in this case means all columns. Can also
be used for all rows

13

Element by element
operations
Can also be used for 2-dimensional arrays
A = B op C means
A(1, 1) = B(1, 1) op C(1, 1)
A(1, 2) = B(1, 2) op C(1, 2)
...
A(n, m) = B(n, m) op C(n,m)
Arrays usually must be same size

Example
ex1 = [1 2 3; 4 5 6]
ex2 = [1 1 1; 2 2 2]
ex3 = ex1 + ex2
ex3 is 2 3 4
6 7 8
ex4 = ex1 .* ex2
ex4 is 1 2 3
8 10 12

Matrix Multiplication
Recall that element -by-element
multiplication is done using the .* operator
Can also do matrix multiplication using the
rules of linear algebra - uses the * operator
If C = A*B:
Number of columns in A must equal number
of rows in B
C will have same number of rows as A and
same number of columns as B

14

## A Row Times A Column

A = [ A1 A2]

B=

C = A1*B1 + A 2 * B 2
Ex: A = [3 - 2]
B=

B1
B2
4
5

C = 3 * 4 + (-2)*5 = 10

Matrix Multiplication
A = A11 A12
A21 A22
C11 =
C12 =
C21 =
C22 =

B = B11 B12
B21 B22

## A11*B11 + A12 * B 21 (row1 * col1)

A11*B12 + A12 * B 22 (row1 * col2)
A21*B11 + A22 * B 21 (row2 * col1)
A21*B12 + A22 * B 22 (row2 * col2)

Matrix Multiplication
Example
A =

1 2
3 4

B= 5
7

C=

(1*5)+(2*7) (1*6)+(2*8)
(3*5)+(4*7) (3*6)+(4*8)

C =

19 22
43 50

6
8

15

## General Formula for

C = A*B
C(1,1) = (row 1 of A) * (col 1 of B)
C(1, 2) = (row 1 of A) * (col 2 of B)
...
C(2, 1)= (row 2 of A) * (col 1 of B)
C(2, 2) = (row 2 of A) * (col 2 of B)
...
To obtain the i,j entry of C, multiply row i of
A by column j of B

Matrix Multiplication in
Matlab
A = [1 4 2; 5 7 3; 9 1 6; 4 2 8];
B = [6 1; 2 5; 7 3];
C=A*B
C=
(note that C has same
28 27
number of rows as A
65 49
and same number of
98 32
columns as B)
84 38

Matrix Multiplication in
Matlab
A = [1 4 2; 5 7 3; 9 1 6; 4 2 8];
B = [6 1; 2 5; 7 3];
D=B*A
Error: number of columns in first matrix
must equal the number of rows in second
matrix. In this case, 2 ~= 4
Note that matrix multiplication is not
commutative: A*B ~= B*A

16

Matrix Division
Identity matrix is all 0's with 1's on the
diagonal. Ex:
1 0 0
0 1 0
0 0 1
Matrix B is the inverse of matrix A if A*B is
the identity matrix.
Inverse of A is represented as A-1

## Matrix Division in Matlab

Left Division X = A\B equivalent to
X = A-1B
Right Division X = A/B equivalent to
X = A B-1

Example: Solving
systems of linear
equations
Solve the following systems of linear
equations:
4x - 2y + 6z = 8
2x + 8y + 2z = 4
6x + 10y + 3z = 0

17

Background
Systems of linear equations can be written
as matrices
4 -2 6
x
8
2 8 2
* y
=
4
6 10 3
z
0
This is of the form AX = B
Solving for X: X = A -1B

Algorithm
Create array A from coefficients on left-hand
side of equations
Create array B from right-hand side of
equations
Solutions = A\B

Matlab Code
A = [4 -2 6; 2 8 2; 6 10 3];
B = [8; 4; 0];
X = A\B
X = -1.8049
0.2927
2.6341

18

Matrix functions
Many, many built-in Matlab functions for use
with vectors and matrices
ones(row, col) - create an array of all ones
zeros(row, col) - create an array of all zeros
A = ones (1, 3)
A=111
B = zeros (2, 3)
B= 000
000

Matrix Functions
mean: finds the mean of a vector
max: finds the max of a vector
min: finds the min of a vector
A = [1 2 3 4 5];
meanA = mean(A )
maxA = max(A)

meanA is 3
maxA is 5

Example
Recall that a row or a column in a matrix is
also a vector, so mean max and min can
be applied to them also
B = [20 30 40; 50 60 70]
max_col1 = max(B(:,1))
min_row2 = min(B(2, 1:3))

19

## More Matrix Functions

length - number of elements in a vector
size - size of an array (rows and columns)
B = [1 2 3; 4 5 6]
lengthB1 = length(B(1, :)) lengthB1 is 3
sizeB = size(B )
sizeB is 2 3

Example- Statistics on
an array
Assume you are a quality assurance
engineer working in a widget factory.
Every hour, you pull 5 widgets off the
production line and weigh them.
Calculate the mean weight, the max weight
and the min weight. Also, determine if
each weight is within its tolerance of 10 lbs
plus or minus 0.1 lb.

Algorithm
Put the widget weights into a vector
Calculate and display mean max and min
For each widget weight
if min >= weight >= max
display OK
else
display out of tolerance

20

Matlab Code
%initialize array with widget weights
Weight = [9.92 10.05 10.08 9.89 10.12];
%calculate and display mean, max and min
weight_mean = mean(Weight );
weight_max = max(Weight );
weight_min = min(Weight );
fprintf ('The mean is %.2f, the max is %.2f and the min is
%.2f \n', weight_mean, weight_max , weight_min)

## Matlab Code (con't)

%loop through array testing tolerances
for j = 1 : 1 : 5
if (Weight(j) >= 9.9) & (Weight(j) <= 10.1)
fprintf ('Widget %i in tolerance', j)
else
fprintf('Widget %i out of tolerance', j)
end
end

21