% Story problem: 2 lbs carrots and 3lbs apples cost $10.15. 1 lb carrots and % 7 lb apples cost $17.12. How much do carrots and apples cost per pound? % eqns are % 2c + 3a = 10.15 % 1c + 7a = 17.12 % To solve in Matlab, write it in matrix-vector form as an Ax=b problem. % A holds the coefficients of the unknowns in the left-hand sideof the eqn % x is the vector of unknowns c and a % b is the vector of known right-hand-side values 10.15 and 17.12 A = [2 3 ; 1 7] A = 2 3 1 7 b = [10.15 ; 17.12] % Solve Ax=b for x using Matlab's "backslash" operator x = A\b x = 1.7900 2.1900 % Verify that the solution satisfies the original equations by using % long-winded high-school arithmetic. First assign the components of % x into variables c and a. c = x(1) c = 1.7900 a = x(2) a = 2.1900 % verify that 2c + 3a = 10.15 2*c + 3*a ans = 10.1500 % verify that c + 7a = 17.12 c + 7*a ans = 17.1200 % Now verify the solution using matrix multiplication % ie verify that Ax = b A A = 2 3 1 7 x x = 1.7900 2.1900 A*x ans = 10.1500 17.1200 % New problem % 1c + 2a + 3t = 18.84 % 2c + 1a = 5.97 % 6a + 2t = 23.52 % Enter this into matlab as an Ax=b problem A = [ 1 2 3 ; 2 1 0 ; 0 6 2] A = 1 2 3 2 1 0 0 6 2 b = [18.84 ; 5.97 ; 23.52] b = 18.8400 5.9700 23.5200 % Solve Ax=b using the backslash operator x = A\b x = 1.6900 2.5900 3.9900 % So the answer is % carrots cost $1.69/lb % apples cost $2.59/lb % tomatoes cost $3.99/lb % Wasn't that a total breeze, compared to solving three equations in three % unknowns by hand? Hooray for numerical linear algebra! % Verify first equation long-windedly c = x(1) c = 1.6900 a = x(2) a = 2.5900 t = x(3) t = 3.9900 1*c + 2*a + 3*t ans = 18.8400 % Now verify all equations by multiplying A*x and comparingto b A*x ans = 18.8400 5.9700 23.5200 A A = 1 2 3 2 1 0 0 6 2 x x = 1.6900 2.5900 3.9900 A*x ans = 18.8400 5.9700 23.5200 b b = 18.8400 5.9700 23.5200 % Observe above that A*x equals b. Can also verify Ax=b by computing % Ax-b and seeing that it's zero % that A*x-b ans = 1.0e-14 * 0.3553 0 0 % Note that Ax-b is not exactly zero. It has magnitude 1e-14, so it's % very nearly zero. That's because the numerical computations are done % in finite precision (there's rounding error). % Question: how do you do subscripts in Matlab? A A = 1 2 3 2 1 0 0 6 2 % access the i,j = 3,2 element of A via A(3,2) A(3,2) ans = 6 % Get second column of A A(:,2) ans = 2 1 6 % In matlab, A(:,j) means all rows in jth col % In matlab, A(i,:) means all cols in ith row A A = 1 2 3 2 1 0 0 6 2 A(1,:) ans = 1 2 3 A(2,:) ans = 2 1 0 A(3,:) ans = 0 6 2 A A = 1 2 3 2 1 0 0 6 2 % Change the 3,1 elem to 99 A(3,1) = 99 A = 1 2 3 2 1 0 99 6 2 % Change the 3rd row to 7, 2, 19 A(3,:) = [7 2 19] A = 1 2 3 2 1 0 7 2 19 % Change the 2nd column to -1 4 6 A(:,2) = [-1 ; 4 ; 6] A = 1 -1 3 2 4 0 7 6 19