Solutions to review questions for Prelim 3 ------------------------------------------ 1. allInterval function B = allInterval(x,a,b) % x is a length-n vector. % B is assigned the value of 1 (true) if every x-value is in the % interval [a,b]. % B is assigned the value of 0 (false) if at least one of the x-values % is not in the interval [a,b]. % Your implementation should make effective use of a while-loop. n = length(x); B = (a <= x(1)) && (x(1) <= b); k = 1; % B is true if x(1),...,x(k) are in the interval... while k MT(3,1), M(7,5 )--> MT(5,7) etc for i=1:5 for j=1:7 MT(i,j) = M(j,i); end end D{k} = MT; end 3. TotalValue % Refer to the Cost-Inventory application in Lecture 15 (3/11). % Complete the following function... function T = totalValue(Inv,Cost) % T is the total value of all the inventory in all the factories [nFact,nProd] = size(Inv); T = 0; for i=1:nFact % Compute the value of factory i’s inventory S = 0; for j=1:nProd S = S + Inv(i,j)*Cost(i,j); end T = T + S; end 4. Checking for numbers in a vector/matrix function B = vecHasNegAndPos(x) % x is a length-n vector and n>=2 % B is assigned the value of 1 (true) if x has at least one component % that is strictly negative and at least one component that is % strictly positive. % Otherise B should be assigned the value of 0. % Your implementation should make effective use of a while-loop. nPos = 0; % Number of positive components found so far. nNeg = 0; % Number of negative components found so far; k = 0; while k 0 nPos = nPos + 1; end if x(k) < 0 nNeg = nNeg + 1; end end B = (nPos>=1 && nNeg>=1); function B = matHasNegAndPos(A) % A is an m-by-n real array with M>=2 and n>=2 % B is assigned the value of 1 (true) if A has at least one component % that has a strictly negative value and at least one component that has a % strictly positive value. % Otherise B should be assigned the value of 0. % Your implemention should make effective use of VecHasNegAndPos [m,n] = size(A); % Place all the values in A into a 1-dimensional array... aVec = [] for i =1:m aVec = [aVec A(i,:)]; end B = VecHasNegAndPos(aVec); 5. TwoClicks % Refer to Lecture 15 (3/11) and the function RandomLink(n). A = RandomLink(1000); % Note that if A(i,j) is one, then there is a link on webpage i % to webpage j. Write a fragment that prints "yes" if it is % possible to go from web page #100 to webpage #200 in one or two clicks. % Thus, if A(100,101) = 1 and A(101,200) = 1 then "yes". if A(100,200)==1 % One click away... disp(’yes’) else % See if it is possible to reach in two clicks % Idea: Check the "1-click" pages to see if they link % to page 200. Quit as soon as success. Found = 0; k =0; while k<1000 && ~Found k = k+1; % Is page k a 1-click page? if A(100,k)==1 % There is a link to page k if A(k,200) == 1 % There is a link on page k to page 200 disp(’yes’) Found = 1; end end end end 6. TopHalf function C = topHalf(A) % Refer to Lecture 20 (4/3). % Suppose A is a length-50 structure array with two fields % Assume A(k).name is a string that names a state and A(k).pop % is an integer whose value is the states population. % Assume that the states are ordered alphabetically. % C is a length-25 cell array of strings that names all the % states whose populations are above the median state population. % The states should be ordered alphabetically in C. % Obtain a vector of populations... pop = zeros(50,1); for k=1:50 pop(k) = A(k).pop; end [y,idx] = sort(pop); % Note that idx(k) is the index of the kth smallest state. % Above-the-median states have indices idx(26),..,idx(50). % Put these indices in a single, length-25 vector Above = idx(26:50); % Without the following step the "big" states wont be assembled in alphabetical % order... Above = sort(Above); % This assembles the state names in C... C = cell(25,1); for k=1:25 j = Above(k); str = A(j).name; C{k} = str; end 7. BigTriplets function N = BigTriplets(A) % Refer to lectures 19 (4/1) and 20 (4/3). % Suppose A is a length-50 structure array with two fields. % Assume A(k).name is a string that names a state and A(k).pop % is an integer whose value is the states population. % We say that three different states form a "big triplet" if % the sum of their populations is greater than 15 million. % N is the number of big triplets. N = 0; for i=1:50 for j=i+1:50 for k=j+1:50 if A(i).pop+A(j).pop+A(k).pop > 15000000 N = N+1; end end end end 8. Reduce function B = Reduce(A) % A is an n-by-n array with n odd and at least 3 in value. % B is obtained by deleting all the even-indexed rows and columns. % Thus if % A = [ 1 2 3 4 5 ;... % 6 7 8 9 10 ;... % 11 12 13 14 15 ;... % 16 17 18 19 20 ;... % 21 22 23 24 25 ] % then % B = [ 1 3 5;... % 11 13 15;... % 21 23 25]v [n,n] = size(A); % Assemble all the odd rows D = []; for i=1:m if rem(i,2)==1 D = [D ; A(i,:)]; end end % Now assemble all the odd columns of D... B = []; for j=1:n if rem(j,2)==1 B = [B D(:,j)]; end end 9. ColorComps A = imread(’LawSchool.jpg’); % Matlab assumes that Red pixel values in first layer, e.g., A(:,:,1) % Matlab assumes that Green pixel values in first layer, e.g., A(:,:,2) % Matlab assumes that Blue pixel values in first layer, e.g., A(:,:,3) [m,n,p] = size(A); % Set up B so image(B) displays the law school but with the rgb values % permuted. In particular, at each pixel, red is displayed at the % green intensity level, green is displayed at the blue intensity level, % and blue is displayed at the red intensity level B = uint8(zeros(m,n,p)); % Write your code fragment here image(B) % Refer to the function Edges from Lecture 17 (3/25). % We want to display the clock tower with the edge pixels highlighted. % To that end, modify the array A so that if B(i,j)>20 then pixel % (i,j) is displayed as white B = Edges(’Tower.jpg’)) % Modify A A = imread(’Tower.jpg’) % Write your code fragment here image(A) Solution: A = imread(’LawSchool.jpg’); % Matlab assumes that Red pixel values in first layer, e.g., A(:,:,1) % Matlab assumes that Green pixel values in first layer, e.g., A(:,:,2) % Matlab assumes that Blue pixel values in first layer, e.g., A(:,:,3) [m,n,p] = size(A); % Set up B so image(B) displays the law school but with the rgb values % permuted. In particular, at each pixel, red is displayed at the % green intensity level, green is displayed at the blue intensity level, % and blue is displayed at the red intensity level B = uint8(zeros(m,n,p)); for i=1:m for j=1:n B(i,j,1) = A(i,j,2); B(i,j,2) = A(i,j,3); B(i,j,3) = A(i,j,1); end end image(B) % Refer to the function Edges from Lecture 17 (3/25). % We want to display the clock tower with the edge pixels highlighted. % To that end, modify the array A so that if B(i,j)>20 then pixel % (i,j) is displayed as white B = Edges(’Tower.jpg’)) % Modify A A = imread(’Tower.jpg’) [m,n,p] = size(A); for i=1:m for j==1:n if B(i,j) > 20 A(i,j,1) = 255; A(i,j,2) = 255; A(i,j,3) = 255; end end end image(A) 10. Longest function [len, ind] = longest(C) % Find the longest string(s) in cell array C. % C is an n-by-1 cell array of strings, n>=1. % len is the length of the longest string in C. % ind is a vector, possibly of length one, containing the index number(s) % of the string(s) with length len % len records the length of the longest string from C{1} to C{k} len = -1; % ind records indicies of strings whose lengths are len ind = []; for k=1:length(C) l = length(C{k}); if l == len ind = [ind k]; elseif l > len ind = k; len = l; end end 11. Shuffle cards % Given the following cell arrays of strings: suits= {’Hearts’, ’Clubs’, ’Spades’, ’Diamonds’}; ranks= {’Ace’, ’2’, ’3’, ’4’, ’5’, ’6’, ’7’, ’8’, ’9’, ’10’, ... ’Jack’, ’Queen’, ’King’}; % Write a code fragment to create a structure array of cards such % that each structure has two fields, suit and rank, that store the % appropriate strings. The structure array should be of length 52. % Do a perfect shuffle of the cards. k=1; % construct the deck of cards for i=1:length(suits) for j=1:length(ranks) cards(k) = struct('suit', suits{i}, 'rank', ranks{j}); k = k + 1; end end % do perfect shuffle on the cards % Note that this definition of a perfect shuffle is different from that % in the lecture. You can use the definition given in lecture. The % important thing is that you are able to work with a structure array. for k=length(cards):-1:1 % choose a random number r in [1,k] % then swap cards(r) and cards(k) r = ceil(k*rand); if r ~= k temp = cards(k); cards(k) = cards(r); cards(r) = temp; end end 12. Point struct % Given a structure array Pts where each structure has two fields, x and y, % sort Pts so that the structures are in the order of % increasing distance from (0,0) n = length(Pts); % compute the distances dist = zeros(n, 1); for i=1:n dist(i)=sqrt(Pts(i).x^2+Pts(i).y^2); end % sort the distances [s, idx] = sort(dist); oldPts = Pts; for i=1:n Pts(i) = oldPts(idx(i)); end