% Solution to Review question 1 % Assume variables nBig and nSm are given % Outer loop to iterate from nBig to nSm for num= nBig:-1:nSm % Check num to see if it is prime d=2; % divisor % Iterate until first proper divisor is found while (mod(num,d) ~= 0); d = d + 1; end if (d == num) fprintf('%d is a prime\n',num); else fprintf('%d\n',num); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solution to Review question 2 %Part A function seconds = hms2s( h, m, s ) % Post: seconds=number os seconds in h:m:s % Pre: h,m,s>=0 seconds = 3600*h+60*m+s; %Part B function [h, m, s] = s2hms( seconds ) % Post: seconds is converted to h:m:s format % Pre: seconds>=0 h = floor( seconds/3600 ); m = floor( mod( seconds, 3600 )/60 ); s = mod( mod(seconds, 3600), 60 ); % Part C Command Window entries and output s = hms2s( 7, 45, 13 ) s = 27913 [h, m, s ] = s2hms( 3682 ) h = 1 m = 1 s = 22 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solution to Review question 3 function [ volume, surfaceArea ] = myCylinder( ratio ); % Post: Calculate volume and surface area of a randomly generated cylinder % where diameter d of cirular end of the cylinder is random in range (0,1) % and height of the cylinder is d*ratio % Pre: ratio>0 d = rand(1,1); % generate diameter in the range (0, 1) height = d*ratio; surfaceArea = 2*0.25*pi*d^2 + pi*d*height; volume = 0.25*pi*d^2*height; % On an exam, these formulas would be given. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solution to Review question 4 %Part A function ave = average(data) % Post: ave= the average of all values in matrix data % Pre: data is at least 1-by-1 [rows,columns] = size(data); sum = 0; for i = 1:rows; for j = 1:columns; sum = sum + data(i,j); end end ave = sum/(rows*columns); %Part B function sd = stdDev(data) % Post: sd=standard deviation of data (vectorized code) % Pre: data is at least 1-by-1 [rows,columns] = size(data); av = average(data); data = data - av; data = data .^ 2; Sum = sum(sum(data)); sd = Sum/(rows*columns); %Alternate solution: nonvectorized function %function sd = stdDev(data) % Post: sd=standard deviation of data (nonvectorized code) % Pre: data is at least 1-by-1 % %[rows,columns] = size(data); %av = average(data); %sum = 0; %for i = 1:rows % for j = 1:columns % data(i,j) = ((data(i,j) - av)^2); % Sum = Sum + (data(i,j)); % end %end %sd = Sum/(rows*columns);