In-Service Workshop on Statistical Methods

Download Report

Transcript In-Service Workshop on Statistical Methods

COS 131: Computing for Engineers
Ch. 3: Vectors and Arrays
Laura Broussard, Ph.D.
Professor
July 7, 2015
1
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV. MATLAB Vectors
V. Engineering Example
VI. MATLAB Arrays
VII. Engineering Example
July 7, 2015
2
I. Introduction
• Emphasizes the basic calculations involving
rectangular collections of numbers in the form of
vectors and arrays.
• You will learn how to:
–
–
–
–
Create them
Manipulate them
Access them
Perform mathematical/logical operations on them
• Shows MATLAB’s ability to deal with sets of
numbers as aggregates as opposed to individually
• Introduces the notion of functions built into the
language
July 7, 2015
3
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV. MATLAB Vectors
V. Engineering Example
VI. MATLAB Arrays
VII. Engineering Example
July 7, 2015
4
II. Concept: Using Built-in Functions
• Function – a named collection of
instructions that operates on the data
provided to produce a result according to
the specifications of that function
• To get help on a particular function, type
the following at the Command window
prompt:
• >> help <function name>
July 7, 2015
5
III. Concept: Data Collections
• MATLAB groups data together in arrays
and in vectors (subsets of arrays)
• Data Abstraction
– Convenient to refer to groups of data as
opposed to individual data items
– Allows the movement of these data as a group
– Allows the use of mathematical and/or logical
operations on these groups
July 7, 2015
6
III. Concept: Data Collections
• Homogeneous Collection
– Arrays and vectors constrain data to only be
accepted for the same data type
– These are referred to as homogeneous
collections; i.e., all data items within a given
array or vector are of the same data type
• We will now consider the basic operations
related to vectors and arrays in MATLAB
July 7, 2015
7
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV. MATLAB Vectors
V. Engineering Example
VI. MATLAB Arrays
VII. Engineering Example
July 7, 2015
8
IV. MATLAB Vectors
• Vector – a list of like data items
(simplest means of grouping)
• Elements – individual items in a vector
• Elements have two attributes:
– Numerical value
– Position in the given vector
• Data type: numbers or logical values
• Vectors also called linear arrays or linear
matrices
July 7, 2015
9
IV. MATLAB Vectors
A.
B.
C.
D.
E.
Creating Vectors
Size (measuring)
Indexing
Shortening
Operations
Arithmetic
Logical
Library
July 7, 2015
Concatenation
Slicing
10
IV. MATLAB Vectors
A. Creating Vectors – 2 methods
1. Creating vectors as a series of constant values
2. Producing new vectors by operating on
existing vectors (later)
July 7, 2015
11
IV. MATLAB Vectors
A. Creating Vectors - from constant values:
• Enter each value directly
A = [1 2 3]
• Enter a range of values with colon operator
B = 1:3:20
• Entering a range of values with linspace(…)
function C = linspace (0, 20, 11)
July 7, 2015
12
IV. MATLAB Vectors
A. Creating from constant values (cont’d.)
• Using functions:
zeros(1,n)
rand(1,n)
ones(1,n)
randn(1,n)
for vectors with 0’s, 1’s, or random numbers
in between
E = zeros(1,4)
Exercise 3.1 Working with Vectors, pp. 49-50
July 7, 2015
13
IV. MATLAB Vectors
A. Creating vectors
• Workspace window information
 The name
 The value
Contents (small vectors) or
Description - such as <1 x 11 double>
 The class (data type) of the vector
• Scalars are vectors (unit length)
July 7, 2015
14
IV. MATLAB Vectors
B. Size of a Vector
– Specific attribute – the length of the vector;
how many elements are in the vector
– Can increase or decrease the size of a vector by
inserting and deleting elements
– Function size(V) when applied to vector V,
returns another vector [r, c]:
r = number of rows (for vectors, 1)
c = number of columns (length of vector)
– Function length(V) returns the length of the
vector
July 7, 2015
15
IV. MATLAB Vectors
C. Indexing a Vector
– Definition: accessing elements of a vector to
assess its value and/or change the value
– Two ways of indexing:
• With a numerical vector
• With a logical vector
– Numerical indexing
• Elements of a vector can be accessed individually or
in groups by enclosing the index of one or more
required elements in parentheses
July 7, 2015
16
IV. MATLAB Vectors
C. Indexing a Vector
– Numerical Indexing: A = [0 2 4 6 8]
• Assessing value: >> A(1)
ans = 0
• Changing value: >> A(1) = 6
A = [6 2 4 6 8]
Exercise 3.2, Extending a vector,
p. 51b
• MATLAB will automatically extend a vector if you
write beyond its current end.
Missing elements zero-filled
Exercise 3.3, Extending a vector, p. 51b
• These examples use a single number to index
July 7, 2015
17
IV. MATLAB Vectors
C. Indexing a Vector
– Numerical Indexing
A = [0 2 4 6 8]
• Indexing can also be with multiple numbers.
>> A(1),(2),(3)
ans = 0 ans = 2 ans = 4
• Use a vector of index values to index another vector
>> B = [ 1 3 5 ]
>> A(B)
ans = 0 4 8
(Note: argument of A is a vector)
• Index vector:
- doesn’t need to match size of vector being indexed
- values must be positive and smaller than length of
vector being indexed
July 7, 2015
18
IV. MATLAB Vectors
C. Indexing a Vector
– Logical Indexing
•
•
•
•
•
July 7, 2015
A = [0 2 4 6 8]
A new (for us) data type.
Two values: true and false
Called Boolean or logical values
Can be assembled into vectors and arrays by
typing in true or false values. MATLAB responds
with 0’s and 1’s
>> mask = [true false false true]
mask = 1 0 0 1
>> A(mask)
ans = 0 6
Logical index vectors can be shorter, not longer.
19
IV. MATLAB Vectors
D. Shortening a Vector
A = [0 2 4 6 8]
– May need to remove elements from a vector
–
Use the empty vector, [ ]
A vector with no elements in it
–
Assign the empty vector to an element in
another vector, that element is removed from
A, and A is shortened by on element
>> A(4) = [ ]
–
July 7, 2015
A = [0 2 6 8]
Exercise 3.4: Shortening a vector, p. 52b
20
IV. MATLAB Vectors
E. Operating on Vectors
– Three techniques analogous to operations on
scalar (single) values:
• Arithmetic operations
• Logical operations
• Applying library functions
– Two unique techniques for vectors and arrays:
• Concatenation (joining)
• Slicing (generalized indexing)
July 7, 2015
21
IV. MATLAB Vectors
E. Operations - Arithmetic
– Can be performed collectively on individual
components of two vectors if
• both vectors are same length or
• one of the vectors is scalar (one value)
– Element by element NOT matrix operations
– Use symbols: .*, ./, and .^
Regular symbols *, /, and ^ reserved for matrix
operations.
July 7, 2015
22
IV. MATLAB Vectors
E. Operations – Arithmetic
– Addition and subtraction same for both matrix
and element-by-element operations
Use the same symbols: + and – Exercise 3.5: Using vector mathematics, pp. 5354
July 7, 2015
23
IV. MATLAB Vectors
E. Logical Operations
– Produce vectors of logical results
– Use to index vectors in a style that makes the
logic of complex expressions very clear
– Can perform element-by-element operations on
two vectors if both vectors are the same length
or if one is a scalar
– A = [2 5 7 1 3] and B = [0 6 5 3 2]
• Where are A’s elements ≥ 5?
•
>> A >= 5
ans = 0 1 1 0 0
•
>> A >= B
ans = 1 0 1 0 1
– Ex 3.6, Working with vector logical expressions, p. 55t
July 7, 2015
24
IV. MATLAB Vectors
E. Logical Operations
– Can be assembled into more complex operations
using logical and (&) and or (|) operators
– Operators come in two flavors
• & / | (single operators)
• && / || (double operators)
• Single operators are for logical arrays of matching
size
• Double operators combine individual logical results,
and are associated with conditional statements (Ch. 7)
– Exercise 3.7, Working with logical vectors, p. 55b
July 7, 2015
25
IV. MATLAB Vectors
E. Logical Operations
– Function find(…)
Inputs an array of logical values
Outputs a vector of positions of true elements
Useful to find indices of the true elements of a
logical vector
– Ex. 3.8: Using the find(…) function, p. 56 t
July 7, 2015
26
IV. MATLAB Vectors
E. Logical Operations
a = [true true false true ]
– Negate the values of all elements of a logical
vector (true ⇒ false and false ⇒ true) with
~ (not operator)
>> na = ~[true true false true]
na = 0 0 1 0
– Each element of na is the logical inverse of the
corresponding original element
– Table 3.1, Operator Precedence, p. 56
July 7, 2015
27
IV. MATLAB Vectors
E. Operations - Library Functions
– MATLAB has a rich collection of mathematical
functions covering mathematical, trigonometric,
and statistical capabilities
– Partial list in App. A
– Complete list – Help menu option
– Accept vectors of numbers rather than single
values and return a vector of the same length
July 7, 2015
28
IV. MATLAB Vectors
E. Operations - Useful Library Functions
– sum(v) and mean(v) consume a vector and
return the sum and mean of all the elements of
the vector
– min(v) and max(v) return two quantities:
the minimum and maximum value in vector
the position of the value in vector
>> [value where] = max([2 7 42 9 -4])
value = 42
where = 2
– round(v), ceil(v), floor(v), and fix(v)
functions that round numbers in vector
July 7, 2015
29
IV. MATLAB Vectors
E. Operations - Concatenation
– MATLAB lets you construct a new vector by
concatenating (joining) other vectors
– A = [B C D … X Y Z]
B, C, D, … are any vector sdefined as a
constant or variable
length of A is sum of the lengths of B, C, D, …
– Resulting vector will be flat, not nested.
– Exercise 3.9: Concatenating Vectors, p. 57b
July 7, 2015
30
IV. MATLAB Vectors
E. Operations: Slicing
– Indexing ≡ basic operation of extracting and
replacing the elements of a vector
– Vectors of indices ⇒ change multiple elements
– Vectors can be:
⋄ previously-defined indices or
⋄ created anonymously as needed
July 7, 2015
31
IV. MATLAB Vectors
E. Operations: Slicing – Anonymous
A = [2 5 7 1 3 4]
–
General form for generating a vector of numbers:
<start> : < increment> : <end>
Omit <increment>, default = 1
Key word end ≡ the length of the vector
Operator : (alone) is short for 1:end
odds = 1:2:end
–
Indexing vector of logical values must be same length or
shorter than the vector being indexed
>> A([false true false true])
ans = 5 1
July 7, 2015
32
IV. MATLAB Vectors
E. Operations - Slicing
– General form of statements for slicing vectors
(copy part of A to part of B)
B(<rangeB> = A(<rangeA>)
– When <rangeA> and <rangeB> are index vectors,
• A is an existing Array
• B can be an existing or new array
or absent altogether (named ans)
• Rules on next slide
July 7, 2015
33
IV. MATLAB Vectors
E. Operations - Slicing
– Rules for use of this template:
• Either
- size of rangeB = size of rangeA or
- size of rangeA = 1
• If B does not exist, it is zero-filled where
assignments not explicitly made
• If B did not exist before this statement, values of A
not directly assigned in rangeB remain unchanged
• See Listing 3.1 on the next slide
July 7, 2015
34
IV. MATLAB Vectors
• Slicing
July 7, 2015
35
IV. MATLAB Vectors
E. Operations – Slicing
– Ex 3.10 Running the vector indexing script, pp. 59-60
– Refer to line by line description on page 59-61.
This will become commonplace in our class discussions
as we examine MATLAB code to understand what the
software is doing.
July 7, 2015
36
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV. MATLAB Vectors
V. Engineering Example
VI. MATLAB Arrays
VII. Engineering Example
July 7, 2015
37
V. Engineering Example – Forces and Moments
• MATLAB vectors are ideal representations of the
concept of a vector used in physics
• Represent each of the vectors in this problem as a
MATLAB vector with three components: the x,
y, and z values of the vector
July 7, 2015
38
V. Engineering Example – Forces and Moments
Examine code to left
and work through
commentary on page
64.
July 7, 2015
39
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV.MATLAB Vectors
V. Engineering Example
VI.MATLAB Arrays
VII. Engineering Example
July 7, 2015
40
VI. MATLAB Arrays
•We now extend the vector ideas to include
arrays of multiple dimensions
•Initially two dimensions
•Each row will have the same number of
columns and each column will have the same
number of rows
•Referred to as arrays to differentiate them from
matrices
•Arrays and matrices differ in the way they
execute their multiplication, division, and
exponentiation operations
July 7, 2015
41
IV. MATLAB Arrays
A.
B.
C.
D.
E.
Properties
Creating
Accessing Elements
Removing Elements
Operations
Arithmetic
Logical
Library
July 7, 2015
Concatenation
Slicing
Reshaping
Linearizing
42
MATLAB Arrays
A. Properties of an Array
– Individual elements in an array are also referred
to as elements
– Unique attributes: value and position
– In a 2-D array position will be (row, column)
– In an n-D array, the element position will be a
vector of n index values
July 7, 2015
43
MATLAB Arrays
A. Properties of an Array
– Function size will return information 1 of 2 forms:
• If called with a single return value
sz = size(A)
It returns a vector of length n containing the size
of each dimension of the array
• If called with multiple return values
[rows, cols] = size(A)
It returns the individual array dimension up to the
number of values requested; ALWAYS provide as
many variables as there are dimensions of the array
July 7, 2015
44
MATLAB Arrays
• Properties of an Array
– The length(…) function returns the maximum
dimension of the array
– The transpose of an m x n array, indicated by
the apostrophe character (‘) placed after the
array identifier, returns an n x m array with the
values in the rows and columns interchanged.
– See example on the next slide
July 7, 2015
45
MATLAB Arrays
• Properties of an Array
Original Array
July 7, 2015
Transposed Array
46
MATLAB Arrays
• Properties of an Array
– Special Cases:
• When a 2-D matrix has the same number of rows
and columns, it is called square
• When only nonzero values in an array occur when
the row and column indices are the same, the array
is called diagonal
• When there is only one row, the array is a row
vector, or just a vector as we saw earlier
• When there is only one column, the array is a
column vector, the transpose of row vector
July 7, 2015
47
MATLAB Arrays
• Creating an Array
– Created by entering values directly
– Created by using one of a number of built-in MATLAB
functions that create arrays with specific characteristics:
• Enter data directly, using a ; to denote the end of a row
• Functions zeros(m,n) and ones(m,n) creates an m x n matrix
with zeros or ones
• Functions rand(m,n) and randn(m,n) fill an array with random
numbers in the range 0 .. 1.
• Function diag(…) where diag(A) of an array A returns its
diagonal as a vector, and diag(V) of a vector returns a square
array with the vector as the diagonal
• Function magic(m) which produces an m x m array which
returns a square array where the values in rows and columns
add up to the same value
July 7, 2015
48
MATLAB Arrays
• Creating an Array
– Exercise 3.11: Creating Arrays
– Smith text, page 67, top
July 7, 2015
49
MATLAB Arrays
• Accessing Elements of an Array
– Elements of an array may be addressed by
enclosing the indices of the required elements
in parentheses, with the first index being the
row index and the second index the column
index
– Can also store values that are elements of an
array as in A(2,3) = 0 will assign the value of 0
to the cell that is at row 2, column 3.
– MATLAB automatically extends the array if
you write beyond its boundaries. Elements
with no values between the boundaries of the
array will be assigned values of zero, 0.
July 7, 2015
50
MATLAB Arrays
• Removing Elements of an Array
– In arrays elements must be removed as comlete
rows or columns
– See page 68 for examples
July 7, 2015
51
MATLAB Arrays
• Operating on Arrays
– Discuss the following (direct extension from
vectors):
• Arithmetic and logical operations
• Application of functions
• Concatenation and slicing
– Two array specific topics:
• Reshaping
• Linearizing
July 7, 2015
52
MATLAB Arrays
• Array Arithmetic Operations
– Can be performed collectively on the individual
components of two arrays as long as both
arrays have the same dimensions or one of them
is scalar (vector length of 1)
– Multiplication, division, and exponentiation
must use the “dot operator” symbols: .*, ./, and
.^. Commas are not used.
– Exercise 3.12: Working with array mathematics
– Smith text, page 69, bottom
July 7, 2015
53
MATLAB Arrays
• Array Logical Operations
– Logical arrays take the same dimensions as
arithmetic arrays
– Result is an array of Boolean values with the
same size as the original array
– Exercise 3.13: Working with array logical
operations
– Smith text, page 70, top
July 7, 2015
54
MATLAB Arrays
• Applying Library Functions
– Most MATLAB mathematical functions can
consume an array of numbers and return and
array of the same dimensions
– As with vectors we have:
• sum(v) and mean(v) – returns sum and mean of each
column
• min(v) and max(v) – min and max values in each
column
• See examples pages 70-71 for details
July 7, 2015
55
MATLAB Arrays
• Array Concatenation
– Can construct new arrays by concatenating
other arrays in the following ways:
• Horizontally, as long as each component has the
same number of rows
• Vertically, as long as each has the same number of
columns; must use semi-colons to denote vertical
concatenation
– The result will be an array with that number of
rows and a number of columns equaling the
sum of the number of columns in each
individual array
– Exercise 3.14: Concatenating an array
– Smith text, page 71, bottom
July 7, 2015
56
MATLAB Arrays
• Slicing Arrays
– General form of statements for moving sections
of one array into sections of another array:
• B(<rangeBR>, <rangeBC>) = A(<rangeAR>, <rangeAC>)
• Where each <range..> is an index vector, A is an existing
array, and B can be an existing array, a new array, or absent
altogether (B = ans)
July 7, 2015
57
MATLAB Arrays
• Slicing Arrays
– Rules for using this template:
• Either each dimension of each sliced array must be equal, or
the size of the slice from A must be 1 x 1.
• If B did not exist before this statement was implemented, it is
zero filled where assignments were not explicitly made.
• If B did exist before this statement, the values not directly
assigned remain unchanged
July 7, 2015
58
MATLAB Arrays
• Reshaping Arrays
– Useful to take an array with one set of dimensions and
reshape it to another set
– Function reshape(…) does this
– Reshape(A, rows, cols, …)
– Takes an array A, whatever its dimensions, and reforms
it into an array sized:
– (rows x cols x …) to as many dimensions as needed
– Does not pad the data to fill any empty space
– Product (rows x cols) of the dimensions of the original
array must equal the product of the new dimensions
– Exercise 3.15 Reshaping an array
– Smith text, page 72, bottom
July 7, 2015
59
MATLAB Arrays
• Linearized Arrays
– MATLAB secret: multi-dimensional arrays are NOT
stored in some nice, rectangular chunk of memory
– Memory block allocated is sequential; stored in column
order
– Can see this in the find(…) function
– See discussion on page 73
– Exercise 3.16: Linearizing an array
– Smith text, page 73, bottom
July 7, 2015
60
MATLAB Arrays
• Array Manipulation Script
Work through the line
by line commentary
on this program. There
is a lot here you should
understand. See pages
75-76
July 7, 2015
61
Ch. 3: Vectors and Arrays
I. Introduction
II. Concept: Using Built-in Functions
III. Concept: Data Collections
IV. MATLAB Vectors
V. Engineering Example
VI. MATLAB Arrays
VII. Engineering Example
July 7, 2015
62
Engineering Example – Computing Soil Volume
• Problem Description – pages 76-77
Landscape Survey
Calculating Soil Volume
July 7, 2015
63
Engineering Example – Computing Soil Volume
• Script to compute total soil
July 7, 2015
64