MATLAB III: More Arrays and Design Recipe
MATLAB III: More Arrays and Design Recipe
4
Arrays as function arguments
5
Powerful Array Functions
6
min, max Examples
• Note: the result is a scalar when the argument is a vector; the result is a 1 x n
vector when the argument is an m x n matrix
7
sum, cumsum vector Examples
8
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a);
9
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a);
10
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a’);
11
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a’);
12
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a(:));
13
What is the value of b?
a = [2 3 1; -2 0 -6; 8 7 -1];
b = min(a(:));
14
sum, cumsum matrix Examples
The sum is the sum for each column; cumsum shows the
cumulative sums as it iterates through the rows
15
prod, cumprod Examples
16
Overall functions on matrices
17
Overall functions on arrays
18
Scalar operations
19
Array Operations
20
Logical Vectors and Indexing
21
Element-wise logical operators
22
True/False
23
Logical Built-in Functions
24
Finding elements
25
Comparing Arrays
26
3D Matrices
27
Functions diff and meshgrid
28
Common Pitfalls
• Attempting to create a matrix that does not have the same number
of values in each row
• Confusing matrix multiplication and array multiplication. Array
operations, including multiplication, division, and exponentiation,
are performed term by term (so the arrays must have the same size);
the operators are .*, ./, .\, and .^.
• Attempting to use an array of double 1s and 0s to index into an
array (must be logical, instead)
• Attempting to use || or && with arrays. Always use | and & when
working with arrays; || and && are only used with logical scalars.
29
Programming Style Guidelines
• Extending vectors or matrices is not very fast, avoid doing this too
much
• To be general, avoid assuming fixed dimensions for vectors , matrices
or arrays. Instead, use end and colon : in context, or use size and
numel
30
DESIGN Recipe
31
Testing
32
assert
33
Examples
• test_triArea.m
• test_myQuadRoots.m
34
Testing is Programming
35
Design Recipe
Design Recipe
36
Example: myFtoC
37
Example: myFtoC
1. Write test_myFtoC
2. Write myFtoC
3. Run test_myFtoC
4. Fix code, re-test until working correctly
5. Look at code, identify any pertinent additional tests
6. Retest, until working correctly
Done!
38
Example: myFtoC
◻ test_myFtoC.m
◻ myFtoC.m
39
Example: quadMin
40
Example: quadMin
41
Example: quadMin
• test_quadMin.m
42