0

I previously posted on how to display and access structure array content. The file consisted of states, capitals, and populations. Now I'm having trouble in created a new structure by organizing these states in alphabetical order. I did this by the sortrows function, and I tried pairing up the values of population and the capitals with the alphabetical states, but I can't seem to get it to be an array. I want it to be an array so I can write it to a file. This is what I have so far:

    fid=fopen('Regions_list.txt')
    file=textscan(fid,'%s %s %f','delimiter',',')
    State=file{1}
    Capital=file{2}
    Population=num2cell(file{3})

sortedStates=sortrows(State)
    n=length(State)

    regions=struct('State',State,...
    'Capital',Capital,...
    'Population',Population)

for k=1:n;
 region=sortedStates(k);
 state_name={regions.State};
 state_reference=strcmpi(state_name,region);
 state_info=regions(state_reference)
end

I hope I'm making myself clear.

2 Answers 2

0

Use this to sort the cell array read in (no conversion needed), then write to file with this.

Sign up to request clarification or add additional context in comments.

Comments

0

With respect to your sorting issue, The function SORT will return as its second output a sort index which can be used to apply the same sort order to other arrays. For example, you could sort your arrays before you create your structure array:

[sortedStates,sortIndex] = sort(State);
regions = struct('State',sortedStates,...
                 'Capital',Capital(sortIndex),...
                 'Population',Population(sortIndex));

Or you could apply your sorting after you create your structure array:

regions = struct('State',State,...
                 'Capital',Capital,...
                 'Population',Population);
[~,sortIndex] = sort({regions.State});
regions = regions(sortIndex);

However, I'm not sure what you mean when you say "I want it to be an array so I can write to a file."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.