3/28a more bonus Matlab material + $for$ loops with a 2-D matrix as the loop range + $cell$ arrays + sieve of eratosthenes (for listing primes up to N), $setxor$, $setdiff$ _______________________________________________________________________________ $for$ loops, revisited the loop range of a $for$ loop can be a 2D matrix: the loop variable is successively assigned each column of the matrix example: z = [3 1 4 ; 2 8 7] for i = z i end _______________________________________________________________________________ $cell$ arrays limitation/restriction of matlab arrays: + arrays in matlab are *homogeneous*: each element in an array must be of the same datatype + arrays in matlab are rectangular: each row is the same size; each column is the same size + note: these limitations are *not* necessarily bad: + rectangular, homogeneous arrays are often faster and smaller + the requirement that all elements be of the same datatype can detect if we accidentally try to store the wrong value in an array matlab $cell$ arrays + $cell$ arrays are built using braces (${$ and $}$) instead of brackets ($[$ and $]$) + $cell$ arrays are *inhomogeneous*: each element can be of a different datatype, including another cell array + a $cell$ array of arrays allows us to simulate/implement arrays that are ragged in one dimension. examples: { 'hi', 5, struct('a', 7, 'b', 28) } % ok [ 'hi', 5, struct('a', 7, 'b', 28) ] % not ok { [3] ; [5 -7] ; [] ; [4 -2 28] } % ok, effectively ragged [ [3] ; [5 -7] ; [] ; [4 -2 28] ] % not ok { 5, { 5 }, '5', { ' 5' } } _______________________________________________________________________________ sieve of eratosthenes + given integer $N>=0$, this is an algorithm to list primes up to $N$ + reminder: 1 is not considered to be prime algorithm: list integers from 1 to $N$ cross 1 off the list for each integer $i$ from 1 to $N$ if $i$ is not crossed off then cross off multiples of $i$ in list starting from $2*i$ list non-crossed-off numbers matlab code (given $N$): list = logical(ones(1,N)); % list(i) == "i is *not* crossed off?" list(1) = 0; % cross 1 off for i = 1:N if list(i) list(2*i:i:N) = 0; end end primes = find(list) revised algorithm: list integers from 2 to $N$ create empty list $primes$ of primes found so far while list is non-empty i <-- first (smallest) element of list put i on list $primes$ delete *all* multiples of i from list (including i) display list $primes$ matlab code for revised algorithm (given $N$): list = 2:N; primes2 = []; while ~isempty(list) i = list(1); primes2 = [primes2 i]; list(rem(list,i) == 0) = []; end primes2 code to check $primes1$ and $primes2$ agree, ignoring order and duplicates: if ~isempty(setxor(primes,primes2)) fprintf('extra values in $primes$: '); disp(setdiff(primes,primes2)); fprintf('\nextra values in $primes2$: '); disp(setdiff(primes2,primes)); end