Solutions Final Review Questions ------------------------------------ %Question 1 function p = pascalVector(lev) % p is the vector corresponding to level lev of Pascal's triangle % % (Mostly) Non-vectorized version p= [1]; % values in level 0 of Pascal's triangle for currentLevel= 1:lev % Temporary vec (q) for current level is one cell longer than prev level q= ones(1,currentLevel+1); % Use the general formula for INTERNAL entries for i= 2:length(p) q(i)= p(i-1) + p(i); end p= q; % Update p end % p=q is actually vectorized. Truly non-vectorized code is: % for i= length(q):-1:1 % p(i)= q(i); % end ---------------------------------- function p = pascalVector(lev) % p is the vector corresponding to level lev of Pascal's triangle % % First build a Pascal's MATRIX, then extract the row m= ones(lev+1, lev+1); for currentLevel= 1:lev for c= 2:currentLevel % "interior" entries only m(currentLevel+1, c) = m(currentLevel, c-1) + m(currentLevel, c); end end p= m(lev+1, :); % p is just the last row of pascal matrix ---------------------------------- function p = pascalVector(lev) % p is the vector corresponding to level lev of Pascal's triangle % % Vectorized version p= [1]; % values in level 0 of Pascal's triangle for currentLevel= 1:lev p = [p 0] + [0 p]; % each level is one cell longer, so shift and add end ------------------------------------ ------------------------------------ %Question 2 % copy scalar v= C{1}; % copy vector for k= 1:length(C{2}) v(k+1,1)= C{2}(k); end % copy matrix currentIdx= length(C{2})+1; [nr, nc]= size(C{3}); for r= 1:nr for c= 1:nc currentIdx= currentIdx+1; v(currentIdx,1)= C{3}(r,c); end end ------------------------------------ ------------------------------------ %Question 3 for n= nBig:-1:nSm % Check n to see if it is prime d=2; % divisor % Iterate until first proper divisor is found while (rem(n,d) ~= 0); d = d + 1; end if (d == n) disp(sprintf('%d is a prime', n)) else disp(sprintf('%d', n)) end end ------------------------------------ ------------------------------------ %Question 4 function MyHistogram(v) % Draw a histogram for the data in v using asterisks in the COMMAND WINDOW. % v is a vector of non-negative values. % The histogram is scaled so that the largest data value is represented by % ten asterisks. Round as necessary in order to draw whole asterisks. % Example: v = [12 4.1 0.5 9.2 20] % Output in Command Window: % ****** % ** % % ***** % ********** multiplier= 10/max(v); scaledV= round(multiplier*v); for r= 1:length(v) astr= ' '; for c= 1:scaledV(r) astr= [astr '*']; end disp(astr) end