Solutions to review questions on structs ---------------------------------------- 1. TopHalf function C = topHalf(A) % Refer to Lecture 21. % 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 2. BigTriplets function N = BigTriplets(A) % Refer to the Lectures 20 and 21. % 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 3. 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