Существует множество способов сделать это. Предполагая, что в файле данных должен быть пробел между age
и =
(как и в других полях), вы можете использовать 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
Затем вы можете обработать данные следующим образом, чтобы создать структурный массив 3 на 1 с полями 'name'
, 'grade'
и '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
Выше используются функции RESHAPE , CELLFUN , STR2DOUBLE и CELL2STRUCT .