% Math22 matlab session example code, alex barnett, 7/25/06 % comments come after the % symbol and are ignored by matlab % Please use text editor to paste chunks of this code into matlab command % window. A = [1 2 3; 4 5 6] % fill the A matrix b = [2;4]; A'*b % matrix mult transpose(A)*b 5*A % scalar mult C = [-1 1 -1;1 -1 1]; A.*C % elementwise mult (note .* not *) A = rand(40,60); % rectangular matrix of random numbers in [0,1] U = rref(U); % compute its REF form spy(U); % show diagram of nonzero entries imagesc(U); colorbar; % show color-scale (density) plot of matrix % handling the workspace: whos save temp.mat clear load temp.mat % LISTS: the colon notation gives a row vector y = 1:10 y = 1:2:10 y = (1:10)' % this gives a column vector % LOOPS % simple loop doing something many times. A = [.9 .1; .1 .9]; x = [1;0]; for i=1:20 x = A*x; end % show the final value of x: x format long g % display more decimal digits! % Problem: we lost all the intermediate values. The next version stores them % Better version, store the complete evolution of x... x = zeros(2,20); % 20 columns since we want x_0, x_1, ..., x_20 x(:,1) = [1;0]; % set the initial values for i=1:19 x(:,i+1) = A*x(:,i); end x % now x has complete history, useful, can plot it... figure; plot(1:20, x(1,:), '+-'); % make a labelled plot with both populations as a function of iterations... figure; plot(1:20, x, '+-'); xlabel('time in yrs'); label('pop in millions');