% This diary demonstrates strategies for entering large matrices % with lots of zero elements, in preparationfor lab 2. % (The *real* way to do this is with 'sparse' matrices --but % we'll get to that later). c = sqrt(2) c = 1.4142 % Suppose we ant to enter a 5 x 5 matrix (25 elements). % You can type in the matrix literally, as we've done before A = [c 1 0 0 0 ; 0 1 -2 1 0 ; 1 0 c 0 0 ; 3 0 0 0 7 ; 0 1 0 -c 0] A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 1.0000 0 1.4142 0 0 3.0000 0 0 0 7.0000 0 1.0000 0 -1.4142 0 % But that's tedious and error prone, and it doesn't scale well % really big matrices. % Here's a better way: Allocate a 5 x 5 matrix of zeros and then % assign the nonzero elements A = zeros(5,5) A = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(1,1) = c A = 1.4142 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(1,1) = c A = 1.4142 1.0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(2,2) = 1 A = 1.4142 1.0000 0 0 0 0 1.0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(2,3) = -2 A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 % etc. That's still a lot of typing. % Here's an even better way: assign all nonzero elems in a row at once A = zeros(5,5); A(1, [1 2] ) = [c 1] A = 1.4142 1.0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(2, [2 3 4] ) = [1 -2 1] A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A(3, [1 3] ) = [1 c] A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 1.0000 0 1.4142 0 0 0 0 0 0 0 0 0 0 0 0 A(4, [1 5] ) = [3 7] A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 1.0000 0 1.4142 0 0 3.0000 0 0 0 7.0000 0 0 0 0 0 A(5, [2 4] ) = [1 -c] A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 1.0000 0 1.4142 0 0 3.0000 0 0 0 7.0000 0 1.0000 0 -1.4142 0 % Now solve Af = b, for the given b. b = [ 0 5 4 -1 2]' b = 0 5 4 -1 2 f = A\b f = -12.0711 17.0711 11.3640 10.6569 5.0305 A*f - b ans = 1.0e-14 * 0 0.1776 -0.5329 0 0 % Awesome! % An even, even better way to do this: SCRIPTS % A script is a list of commands in a file that % Matlab will execute sequentially % I will write a file name 'solveAfb.m' that does the row % assignments as performed above clear all solveAfb f = -12.0711 17.0711 11.3640 10.6569 5.0305 clear all % Note that the script has created new variables A,b,c, and f. who Your variables are: A b c f A A = 1.4142 1.0000 0 0 0 0 1.0000 -2.0000 1.0000 0 1.0000 0 1.4142 0 0 3.0000 0 0 0 7.0000 0 1.0000 0 -1.4142 0