Lecture 22 Matrix Algebra i Consider adding matrices
Lecture 22 Matrix Algebra
(i
Consider adding matrices A and B A= 1 4 2 5 3 6 B= 2 8 4 10 6 12 >> A+B ans = 3 6 9 12 15 18 Write a function addm(A, B) that computes A+B using for loops >> addm(A, B) ans = 3 12 6 9 15 18 (c) 2007 -08 Brian Funt, Simon Fraser University
Strategy for addm Must visit every element of the matrix Use a for loop to index each row. Call the index r Use a second (nested) for loop to index each column of each row Call the index c Given an r and c, compute SM(r, c) = A(r, c)+B(r, c) (c) 2007 -08 Brian Funt, Simon Fraser University
Matrix Addition Example with Error Checking %addm(A, B) returns the matrix addition A+B function SM = addm(A, B) SM=[]; %Return empty matrix if there’s an error of any sort. rows=size(A, 1); cols=size(A, 2); %Comparison of sizes is vector comparison of both rows and columns if size(A) == size(B) for r = 1: rows for c = 1: cols Nested loop SM(r, c)=A (r, c)+B(r, c); end else disp('Error: matrix dimensions do not match. '); end (c) 2007 Brian Funt, Simon Fraser University
Example of addm A= 1 4 2 5 3 6 >> addm(A, A) ans = 2 8 4 10 6 12 (c) 2007 -08 Brian Funt, Simon Fraser University
Efficiency (lack thereof) of Explicit Loops a=ones(1000); >> tic; addm(a, a); toc Elapsed time is 18. 415547 seconds. >> tic; a+a ; toc Elapsed time is 0. 028919 seconds. >> 18. 4/. 029 ans = 634. 4828 (c) 2007 Brian Funt, Simon Fraser University
Pre-Allocating Space Helps Alot %addm 2(a, b) returns the matrix addition a+b function sm = addm 2(a, b) sm=[]; rows=size(a, 1); cols=size(a, 2); %Comparison of sizes is vector comparison of both rows and columns if size(a) == size(b) sm = a; %allocate space for matrix sm by copying a for r = 1: rows for c = 1: cols sm(r, c)=a(r, c)+b(r, c); end else disp('Error: matrix dimensions do not match. '); end >> tic; addm 2(a, a); toc Elapsed time is 0. 096590 seconds. >> tic; a+a; toc Elapsed time is 0. 027277 seconds. >> tic; addm(a, a); toc Elapsed time is 18. 415547 seconds.
To Try (1)Using explicit looping, write a function multscalar(M, s) that takes as arguments a matrix, M, and a scalar, s, and returns a matrix that represents the product s*M (2)Using nested explicit looping, write a function summatrix(M) that returns the sum of all the elements of M (c) 2007 -08 Brian Funt, Simon Fraser University
- Slides: 34