Announcements P3 due today P4 has been handed out (and it involves some Matlab programming as well as Java) Extra credit assignment handed out tomorrow, due Monday Quiz today CS 100 Lecture 15
Today’s Topics Review Matlab, Matlab and more Matlab CS 100 Lecture 15
Review Matlab -- powerful tool for numerical computations and some snazzy graphics variables -- do not need to be declared constants: pi, Inf, NaN arrays: a = [1 2 3]; b = [a, 4, 5, 6]; c = 1:2:10; d = c(2:4) CS 100 Lecture 15
Array functions There are many functions to compute facts about arrays. min(x), max(x), mean(x), ... Array Operations Basic operations on arrays are performed element-by-element. Example: function applications: x = [4.2 7.89 2.4 -42.1 ] floor(x) An operation may involve an array and a scalar. The operation is performed on each element of the array and the result is an array of these values. x / 2 CS 100 Lecture 15
Array Operations Operations may combine two arrays if they have exactly the same length. x = [1 3 5 7] y = [10 20 30 40] x + y y - x The operations + and – work as expected. For element-by-element multiplication, division, and exponentiation, use .* , ./ , and .^ . (Explanation: The usual operators * , / , and ^ perform matrix [Linear algebra] operations between arrays. We will not cover that in CS100.) CS 100 Lecture 15
Multiple Subscripts In general, an array of integers can be used as a subscript. The result is an array consisting of the elements selected by the subscripts in the order given. a = 10 * [0:9] -- 0 10 20 30 …. 90 a([3 4 5]) -- 20 30 40 a(3:5) -- 20 30 40 a([5 4 3]) -- 40 30 20 a([1 1 7 4 6]) -- 0 0 60 30 50 a(10:-1:1) -- 90 80 70 . . . . 0 CS 100 Lecture 15
Logical Ops and Arrays Logical operations yield 0 (false) or 1 (true). When performed on arrays, an array of 0’s and 1’s is the result. a = [5 8 6 12 9] b = [2 3 6 7 10] a > b a ~= b a > 5 rem(a, 3) rem(a, 3) == 0 The functions any and all yield 1 if, respectively, any or all of the elements in their array argument are non-zero CS 100 Lecture 15
Managing the Session clc Clears the Command window clear Removes variables from memory help name Searches online help for the topic name lookfor name Searches the help entries for the specified keyword name quit Stops Matlab who Lists the variables currently in memory whos Lists the current variables and sizes, and indicates whether they have imaginary parts CS 100 Lecture 15
Basic plotting (no, not conniving) If x and y are two arrays with the same number of elements, plot(x,y) draws a plot of x (horizontal) vs y (vertical) x = linspace(0, 4*pi, 250); y = sin(x); plot(x,y) Normally the graph is scaled so the full range of x and y values fill the plot. To have equal spacing on the axes, enter axis(‘equal’) after the plot has been drawn (using straight quote marks). You can label the axes and title the graph after it has been drawn: xlabel(‘x axis label’) ylabel(‘y axis label’) title(‘A Fabulous Graph’) CS 100 Lecture 15
Plot Options The plot command has an optional third argument that can be used to specify the line color and style. Examples: v = -10:0.5:10; fv = 3*pi*sin(v).^2 - v; plot(v, fv, ‘g’); % green line plot(v, fv, ‘b:’); % blue dotted line plot(v, fv, ‘r+’); % red crosses plot(v, fv, ‘c--’); % cyan dashed line Use help plot to find other possibilities CS 100 Lecture 15
Multiple Plots Normally each new plot is drawn in a blank window, replacing whatever is there. Use hold on to retain the previous plot so you can draw a new one over it. Use hold off to release the previous plot so the next one will appear in a blank window. Example: x = linspace(0, 6*pi, 1000); y = sin(x); z = cos(x); plot(x, y, ‘r’); hold on plot(x, z, ‘g’); CS 100 Lecture 15
2-D arrays -- Matrices Matlab’s basic data structure is a 2-D array of numbers (1-D arrays are a special case of this). There are various ways to create 2-D arrays. Easiest is to list the rows separated by semicolons: a = [1 2 3 4; 5 6 7 8; 9 10 11 12] Functions are provided to construct arrays with m rows and n columns initialized in various ways. ones(m,n) % m by n 1’s zeros(m,n) % m by n 0’s rand(m,n) % m by n random % numbers in the range % 0.0 to 1.0. If A is a 2-D array, size(A) is a 1-D array containing the number of rows and columns in A. CS 100 Lecture 15
Subscripting in two dimensions Individual elements of a 2-D array a are accessed by listing the row and column numbers in parentheses a(1,3) a(3,1) a(2,2) Entire rows and columns can be accessed using a colon as a “wildcard” a(2, :) a(:, 3) CS 100 Lecture 15
More on subscripting The colon operator can be used to access arbitrary slices of an array. a(2:3, 1:2) % rows 2-3, cols 1-2 a(1:2, 4) % rows 1-2, col 4 a(1:2, :) % rows 1-2, all cols It can also be used to change the shape of an array by deleting rows, columns, or sub-matrices of a matrix. a(1:2, :) = [] % removes rows 1-2 % from a CS 100 Lecture 15
Combining and Transposing 2-D Arrays If A, B, C, and D are arrays, [A B] or [A , B] is an array formed by combining the columns of A and B with A on the left. A and B must have the same number of rows. [C ; D] is an array formed by stacking the rows of C above the rows of D. C and D must have the same number of columns. If A is an array with m rows and n columns, A’ (A quote-mark) is an array with n rows and m columns with A’(i,j) = A(j,i). The result is known as the transpose of A. CS 100 Lecture 15
Examples C = [A B] 1 2 3 10 11 12 4 5 6 13 14 15 D = [A;B] 1 2 3 4 5 6 10 11 12 13 14 15 A = 1 2 3 4 5 6 B = 10 11 12 13 14 15 D’ = 1 4 10 13 2 5 11 14 3 6 12 15 CS 100 Lecture 15
Functions and 2-D Arrays Functions like sqrt, sin, cos that operate element-by-element on 1-D arrays work the same on 2-D arrays. m = 10 * rand(5,4) sqrt(sin(m)) Functions like sum, prod that produce a scalar result from a 1-D array produce a 1-D array result when applied to a 2-D array. The function is applied to columns of the 2-D array. a = [1 2 3; 4 5 6; 7 8 9; 10 11 12] sum(a) -- 22 26 30 To apply these functions to rows in a 2-D array, transpose the array with the quote operator. sum(a’) -- 6 15 24 33 CS 100 Lecture 15
Control Structures Like most programming languages, Matlab has loops and conditional statements, although these are needed far less often because of the available array operations. The punctuation differs from Java. if statement basic form: if logical expression statements end Example: if x > y temp = x; x = y; y = temp; CS 100 Lecture 15
Else if-else statement basic form: if logical expression statements else statements end Example: if x > y temp = x; x = y; y = temp; else end CS 100 Lecture 15
while while statement basic form: while logical expression statements end Example: while k>0 sum = sum + k; k = k - 1; end CS 100 Lecture 15
for The colon operator (or any array for that matter) can be used to generate index values for a loop. Example: Create an array with each element a(i,j) initialized to i+j. We allocate the array first to avoid array index out-of-bounds errors. a = zeros(25, 15); for r = 1 : 25 for c = 1 : 15 a(r,c) = r + c; end CS 100 Lecture 15
Creating new functions -- .m files New functions can be defined by storing the commands to compute them in a file with a name that exactly matches the function name followed by .m . Function definition syntax: function [output vars ] = function_name ( input vars ) Example: File sqr.m. function [result] = sqr(x); % yield the square of the values in x result = x .* x; All variables are local to the function. Comments that immediately follow the function definition line are used by help and lookfor Functions may be applied to any Matlab data and will be applied element-by-element automatically if appropriate. CS 100 Lecture 15
3-d plots plot3 function is used -- same format as plot, except 3 dimensions t = 0:pi/50:10*pi; plot3(sin(t), cos(t), t) CS 100 Lecture 15
mesh, surf. . .cool pictures Do help mesh/help surf for info CS 100 Lecture 15