% This m-file is a tutorial on loops and control structures clear %% Basic for loop for j = 1:4 v(j)=j; end v %% Do operations on matrix elements using a loop A = [ [1 2 3]' [3 2 1]' [2 1 3]'] % Define a matrix % Re-define matrix for j=2:3 A(j,:) = A(j,:) - A(j-1,:) end %% Nested loops for j = 1:3 for i = 1:3 B(i,j) = i^2-j end end %% While loop % Find all powers of 2 less than 10000 v=1; num=1; j=1; while num < 10000 num = 2^j; v = [v ; num]; % Add num to list j=j+1; % Increment counter end v j %% If-elseif-else decision statements i=6; j=21; if i>5 k=i; elseif (i>1) & (j==20) k=5*i+j; else k=1; end k pause % Break command in a for loop for i=1:length(v) if v(i)>2000 break % terminate loop else v(i) = v(i)^2+1; end end v %% Switch-case decision statements colour=input('colour = ','s'); switch colour case 'red' c = [1 0 0]; case 'green' c = [0 1 0]; case 'blue' c = [0 0 1]; otherwise error('invalid choice of colour'); end c