% Data file statePop.txt contains state names and state population figures
% and the states are listed in alphabetical order. Write a similar text
% file with the states ordered from smallest to largest population.

C = file2cellArray('StatePop.txt'); % C{i} is the name and pop of state i
% C{i} is a string
% Extract population data as numbers
n = length(C);
pop = zeros(n,1);
for i=1:n
S = C{i};
pop(i) = str2double(S(16:24)); % pop(i) is the population of state i
end

% Sort state pop
[s,rank] = sort(pop);

% New cell array with state data sorted from small to large by population
Cnew = cell(n,1);
for i=1:n
ithSmallest = rank(i);
Cnew{i} = C{ithSmallest};
end

cellArray2file(Cnew,'statePopSm2Lg.txt')