Firstly, I have the user input their own text files consisting of states, capitals, and populations and I put all of these values into a structure array using the following code:
clear
clc
%Part A
textfile=input('What is the name of your text file?\n','s');
fid=fopen(textfile);
file=textscan(fid,'%s %s %f','delimiter',',');
State=file{1}
Capital=file{2}
Population=file{3}
regions=struct('State',State,...
'Capital',Capital,...
'Population',Population)
fclose(fid);
My first question: is it possible to display all of the values in the structure? Displaying the structure array just gives me this:
50x1 struct array with fields:
State
Capital
Population
And my second question: is it possible for me to access information in this structure by trying to find, for example, 'California'
only?
As you've already discovered, the default display of structure arrays in MATLAB doesn't tell you much, just the array dimensions and field names. If you want to see the contents, you'll have to create formatted output yourself. One way you can do this is to use STRUCT2CELL to collect the structure contents in a cell array, then use FPRINTF to display the cell contents in a particular format. Here's an example:
With regard to your second question, you can collect the entries from the
'State'
fields in a cell array, compare them to a given name with STRCMP to get a logical index, then get the corresponding structure array element:NOTE:
As you mention in a comment, each
'Population'
entry in your structure array ends up containing the entire 50-by-1 vector of population data. This is likely due to the fact thatfile{3}
in your sample code contains a vector, whilefile{1}
andfile{2}
contain cell arrays. In order to properly distribute the contents of the vector infile{3}
across the elements of the structure array, you need to break the vector up and place each value in a separate cell of a cell array using NUM2CELL before passing it to STRUCT. DefiningPopulation
like this should solve the problem: