Question

I have a text file and would like to import it into MATLAB and make it a list:

Person1
name = steven
grade = 11
age= 17

Person2
name = mike
grade = 9
age= 15

Person3
name = taylor
grade = 11
age= 17

There are a few hundred entries like these above. Each are separated by a blank line. I was thinking I could scan the text and make the information between each blank line into an item in the list. I also would like to be able to look up each person by name once I have a list like the one below.

I want something like:

x = [Person1         Person2       Person3      
     name = steven   name = mike   name = taylor
     grade = 11      grade = 9     grade = 11
     age = 17        age = 15      age = 17]

This seems very straight forward but I have been having trouble with this so far. I may be overlooking something. Anyone have any ideas or advice?

Was it helpful?

Solution

There are many ways you could potentially do this. Assuming there is supposed to be a space between the age and = in the data file (like the other fields), you could use TEXTSCAN:

fid = fopen('people.txt','r');           %# Open the data file
peopleData = textscan(fid,'%s %*s %s');  %# Read 3 columns of strings per row,
                                         %#   ignoring the middle column
fclose(fid);                             %# Close the data file

Then you could process the data in the following way to create a 3-by-1 structure array with fields 'name', 'grade', and 'age':

nFields = 3;                                       %# Number of fields/person
fields = peopleData{1}(2:nFields+1);               %# Get the field names
peopleData = reshape(peopleData{2},nFields+1,[]);  %# Reshape the data
peopleData(1,:) = [];                              %# Remove the top row
peopleData(2:nFields,:) = cellfun(@str2double,...  %# Convert strings to numbers
                                  peopleData(2:nFields,:),...
                                  'UniformOutput',false);
x = cell2struct(peopleData,fields,1);              %# Put data in a structure

The above uses the functions RESHAPE, CELLFUN, STR2DOUBLE, and CELL2STRUCT.

OTHER TIPS

Create a 'person' structure with fields 'name', 'grade', and 'age'

Then use fgetl in combination with regexp almost exactly like your previous question about genes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top