EN 001-: Introduction to Computational Design Fall 2017 Tufts University Instructor: Soha Hassoun soha@cs.tufts.edu Matrices & vectors Matlab is short for MATrix LABoratory. In Matlab, pretty much everything is actually a matrix. So one would expect Matlab to work well with matrices. By and large, that s true. But first, of course what is a matrix & why do we care? 1 2 What is a matrix and a vector? A vector is an ordered, indexed group of variables that share the same name. It's like a variable, but with a bunch of buckets in a row that are all numbered. Other languages call it an array. Example: vec1 = [1 3 7]; We use brackets to declare a vector but parentheses to access it! Then vec1(1) is 1; vec1(2) is 3; vec1(3) is 7. This is a row vector (your high-school math teacher may have also taught you about column vectors). Terminology: the individual elements of the vector are called, well, elements. Our vec1 has 3 elements. 3 Why do we care about vectors? A vector lets you collect a bunch of similar things, refer to them by one name, and operate on all of them at once. Consider the grades of a -student class for HW1: HW1_a=90; HW1 = [90,99,0,90]; HW1_b=99; HW1_c=0; HW1_d=90; Which format would you rather work with? What if there were 100 students rather than? But wait, there s more Consider the same deal for HW2: HW2 = [91,80,55,93]; HW2_a=91; HW2_b=80; HW2_c=55; HW2_d=93; What if you want the average? avg=(hw1+hw2)/2; Works no matter how many students there are! Yes it does! Avg_a=(HW1_a+HW2_a)/2; Avg_b=(HW1_b+HW2_b)/2; Avg_c=(HW1_c+HW2_c)/2; Avg_d=(HW1_d+HW2_d)/2; 5 Vector-scalar operations vec1=[1 3 7 5]; vec1 = vec1 * 1.1; Perhaps we re storing how much money everyone has, and they all got 10% interest. What do you think this would do? vec2 = vec1 + 1.1; 1
Vector-vector operations vec1=[1 3 7 5]; vec2=[2 2 1 1]; What do you think these would do? vec3 = vec1 + vec2; vec3 = vec1 * vec2; vec3 = vec1.* vec2; It s illegal to multiply two row vectors. We ll see why shortly The.* operator does element-by-element multiplication on two vectors Where else might vectors be useful? Any other ideas where vectors might be useful? Height of 100 patients (or weight) Temperature of each day of the year Really, most any time you want to keep track of a big bunch of items 7 8 More tricks with vectors vec1 = 2:; % same as [2 3 5 ] vec1 = 2:3:12; % same as [2 5 8 11] Hmmm this is the same notation as for i=2: for i=2:3:12 What do you think this code would do? vec1=2:; for i=vec1 stuff end exactly the same as for i=2: stuff end Under the hood, a for loop merely iterates through the elements of a vector! Just a reminder Let's write this down I've gotten it wrong about a hundred times already myself: You usually create matrices using brackets: mat=[1 2 3] You access matrices using parenthesis: mat(1) If you get it backwards, you'll get an error message that may not be incredibly clear. 9 10 Still more tricks with vectors vec1 = 2:3:12; vec1(1); vec1(3); vec1(2:3); numel(vec1); vec1(2)= ; vec1(2)=[]; vec1 = [1,2 3]; Concatenating vectors vec1=[1 3 7 5]; vec2=[2 2 1 1]; vec3 = [vec1 vec2]; vec3 = [1 3 7 5 vec2]; vec3 = [vec1 2 2 1 1]; 11 12 2
Strings are really vectors! A string is just a row vector str = 'abcd' str = ['ab' 'cd'] str=['a' 'b' 'c' 'd'] str=['ab' 'cd'] str=strcat('ab','cd') Deleting pieces There is an empty vector: []. vec1=[1 3 7 5 9 5]; vec1(3)=[]; vec1(2:3)=[]; Of course, the same works with strings name='wilbur'; name(:)=[]; name(3)='nnie'; 13 1 A bit of confusion disp(i) disp(i*i) That's because 'i' is the square root of -1 in math. i=3; disp(i) sqrt(-1) The motto: Matlab has a default meaning for 'i', but you can overrule it if you want. It works the same for vectors sqrt() sqrt = [2 8 10]; sqrt() Just like before, there is a default meaning for sqrt, but you can overrule it! The thing that "sqrt" refers to can change over time. another example: you can set var=1 and later set var='abc'; the same variable can change from number to string. 15 1 On to matrices A vector is just 1 dimension We showed a row vector; we ll also do column vectors. A matrix is 2 dimensions (a rectangular array) mat1 = [1 2 3; 5 ] yields Each ; starts a new row. 1 2 3 5 Why might we want matrices? What are some uses for matrices? 17 18 3
A matrix as a bunch of rows Column vectors We could do: HW1 = [90,99,0,90]; HW2 = [91,80,55,93]; Or just do HW= [90,99,0,90; 91,80,55,93] colvec = [1; 3; 7] 3x1 column vector It s just a matrix with 3 rows and one column. 1 3 7 19 20 Tricks with matrices Repmat HW= [90,99,0,90; 91,80,55,93]; size(hw) % numel(hw) % HW(2,3) % HW(:,2) HW(1,2:3) HW([1 2],[2 ]) Repmat() repeats a matrix. Assign my_mat=[1 5 3;2 1 ] repmat(my_mat, 2,1) repmat(my_mat, 1,2) repmat(my_mat,3,2) 1 5 3 2 1 21 22 It all starts to make sense Appending matrices, take 2 Remember when we did repmat ('*',1,3) to make '***'? '*' is a 1x1 matrix with (1)='*'. repmat('*',1,3) repeats that matrix 3 times gives us a matrix with (1)='*', (2)='*', (3)='*'. And this is just the string '***'. Similarly, repmat ('ab',1,2) 'abab' mat1=[1 2;3 ] mat2=[5 ; 7 8] [mat1 mat2] [mat1; mat2] 1 2 3 5 7 8 23 2
Not everything can be appended a=[1 2 3]; [1 2 3] b=[; 5; ]; [a b] 5 Matrix multiplication Review from high school (hopefully J) i th row, j th column = i th row j th column 1 2 3 * 2 = 28 (1*2 + 2* + 3*) 1 2 3 * 5 7 8 = 19 22 3 50 (e,g., 2 nd row 1 st column = (3 )*(5 7) = 3*5 + *7 = 3 25 2 More matrix multiplication Column vectors and transposes Not all arrays can be multiplied (the matrices must be conformal): [1 2 3] * [ 5 ] 1 2 3 * 5 = illegal 1 2 3 * 5 = illegal Why? Any row of [1 2 3] has 3 elements, but any column of [ 5 ] has only 1 element, so you cannot take their dot product. E.g., 1 st row, 1 st column would be (1 st row of [1 2 3])*(1 st column of [ 5 ]) = 1* + 2*? + 3*?. It doesn't work. 27 [1 2 3] * [; 5; ] [1 2 3] * [ 5 ]' 1 2 3 * 2 = 28 28 Transposes in general.* means element by element You transpose any matrix by switching rows & columns. So for any matrix my_mat, we have my_mat(r,c) = my_mat'(c,r) my_mat=[1 5 3;2 ] 1 5 3 2 my_mat' 1 2 5 3 [1 2 3] * [ 5 ] [1 2 3].* [ 5 ] 1 5 3 2 1 2 3 * 5 = illegal 1 2 3.* 5 = 10 18 1 1 2.* = 1 5 2 1 1 29 30 5
System of equations: 2x + 3y = 1 1x + 2y = 8 Matlab version a=[2 3; 1 2]; b = [1; 8]; Linear equations 2 3 1 2 a \ b % solves the equations and returns [; 2] Chooses between several different solvers, depending on the matrices you give it. x y = 1 8 Yeah, matrices might even be useful J Linear indexing Matlab's linear indexing lets you access a matrix with just one index. 1 3 5 7 Normal: HW= [90,99,0,90; 91,80,55,93]; HW(2,3) is 55 Linear indexing: HW(2) is 91, and HW(3) is 99 and HW(8) is 93, and HW([2 5]) is [91 0]. But why did they do this? Any thoughts? 2 8 31 32 The find() function vec=find (HW>90) % Returns a vector of indices of those elements that meet the condition HW(vec) % So we have an easy way to find elements of a matrix that meet a condition. Or, even easier, HW(find(HW>90)) yields [91 93 93]. sum() The sum() function sums up each column and returns a row vector. sum(hw) [181 179 115 183] It will also sum a column vector into 181 179 115 183 a single number (as expected) It will also sum a row vector into a single number! 90 91 90 91 181 181 33 3 Stuff to explore yourself A few more functions you can explore yourself : prod(): like sum(), but multiplies max(): like sum(), but takes the max inv(): matrix inversion ones(), zeros(), eye(): build some simple matrices Group activity; what does this code do? HW = HW+1 HW(find(HW<5)) = 70 HW(find(HW<5) = HW(find(HW<5)) + 5 HW(:, find(sum(hw)/2 <85)) = [] 35 3
Matrices and dog barf Uninitialized variables caused an error >> clear >> a Undefined function or variable 'a'. Does the same apply to matrices? >> clear >> b(2,3) Undefined function or variable 'b'. So, yes it does; but there's more to it than that. Initializing matrices a = [3,,9]; Creates a 1x3 vector and initializes it all at once. b = zeros(3,5); Creates a 3x5 matrix of zeros c(10)=1; what does this do? no possibility of eating dog barf 37 38 Social networks Let s talk about social networks. What are the big social-network sites? Do they have a concept of a friend? Is friend always symmetric? Are there different levels of friendship? How might we store the network? Our network will be simple Friendship is always symmetric You're either friends or not. That's all. Some thoughts on how to organize the data: A row vector. Each element is a string such as AmyN,BillJ (meaning that Amy and Bill are friends) A matrix. People get numbered. The friendship level between person #i and #j is stored at mat(i,j). Other ideas? 39 0 Group activity How might you find how many friends Dan has? How might you find out how many people have no friends at all? (hint: you don't need any loops) Ann Bill Cat Dan Ann 0 0 1 1 Bill 0 0 0 0 Cat 1 0 0 1 Dan 1 0 1 0 1 7