%% Programming Languages Matlab 3101 - Class 2 % 3/12/08, Instructor: Blake Shaw %% Review % can make variables, numbers, lists, matrices, can index them in % interesting ways, and apply mathematical functions to them % working with variables 3+4 a = 5 b = 7; x = a^b %working with lists list1 = 3:5:94 list1 .^ 2 [list1(1:5).^2, list1(6:end).^3] % basic eigenvalue decomposition A = rand(10, 10); [v, d] = eig(A); % lets factor and recompose a large number x = factor(345345435); prod(x) %% control flow in scripts % if, for, while, try, catch a = 3; b=4; a > b (a= b %% if statements % if/else, booleans with ands and ors, and other relational operators A = floor(10*rand(2, 2)); B = floor(10*rand(2, 2)); if (sum(A, 1) > 3) X = 4; else X = 5; end if (a < 100) && (b < 5) X = 1000 else X = 0 end if (a < 100) || (b < 2) X = 1000 else X = 0 end if (a<100 && (b-10) ~= -3) || a == 6 X = 1000 end if X > 0 && eig(X) <= -1 X = 1000 end %% while loops % similar to if statements... careful about infinite loops, contorl-c to % exit x = 100; while x > 50 x = x - log(x) end % this is an infinite loop -- it runs forever!!! %{ % these are also multiline comments! while 1 x = x+1; end %} %% for loops % count up, count down, and by different increments 1:1 3:36 3:2:36 45:-3:0 for i=1:5 i X = rand(i, i); sum(sum(X)) max(max(X)) end % some stuff does not need to be looped for i=1:2:8 i^2 end (1:2:8).^2 indices = ceil(100*rand(10, 1))'; X = (1:100).^2; runningTotal = 0; for i=indices i runningTotal = runningTotal + X(i); end runningTotal % write without a loop? runningTotal2 = sum(X(indices)) N=10; A = rand(N, N); for i=1:N for j=1:N A(i, j) = A(i, j)^2 + sin(pi * (i/N)); end end for i=1:30 if i < 15 x = 5; end end %% try and catch % good for catching and dealing with errors for i=1:10 A = rand(10, 3); B = rand(5, ceil(3*rand())); try result = A * B'; catch disp('Loop caused an error'); disp(sprintf('Size of B: %f', size(B, 2))); end end result %% disp and sprintf, helpful printing in loops % like c, %g, %d, %s X = 5; disp(X) X = [1, 34, 54, 6] disp(X) disp('this is a string'); X = 5; disp(sprintf('X is equal to %d and some number is %d', X, 10)); str = 'blake'; x = length(str); disp(sprintf('"%s" has %d characters', str, x)) x = [1, 234, 3,4, 34]; disp(sprintf('x is equal to %d\n', x)) pi disp(sprintf('%1.100g', pi)) %% formatting ouput with the format command % short, long %% more practice with creating matrices % zeroes, ones, eye, diag, linspace, : %% more practice with creating indexes % :, randperm, sub2ind, ind2sub %% more plotting % using imagesc to plot a matrix, or spy, title plots, set axes, change colormap, % specify which figure A = rand(10, 10); A(2, :) = 0; imagesc(A) colormap('gray'); title('my random matrix'); A(find(A > 0.2)) = 0; spy(A) %% avoiding loops % repmat, find N = 10; x = 1:N; repmat(x, N, 1)