登录论坛

查看完整版本 : 如何在MATLAB中将此文本文件制成列表?


poster
2019-12-10, 20:41
我有一个文本文件,想将其导入到MATLAB中并使其成为列表:

Person1 name = steven grade = 11 age= 17 Person2 name = mike grade = 9 age= 15 Person3 name = taylor grade = 11 age= 17 上面有几百个条目。每个都由空白行分隔。我当时想我可以扫描文本并使每个空白行之间的信息成为列表中的一个项目。我也希望能够按名称查找每个人,只要我有以下列表。

我想要类似的东西:

x = [Person1 Person2 Person3 name = steven name = mike name = taylor grade = 11 grade = 9 grade = 11 age = 17 age = 15 age = 17] 这似乎很简单,但是到目前为止,我一直在遇到麻烦。我可能忽略了一些东西。任何人有任何想法或建议吗?



回答:

您可以通过多种方式执行此操作。假设数据文件中的age和=之间有一个空格(就像其他字段一样),则可以使用TEXTSCAN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/textscan.html) :

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 然后,您可以按照以下方式处理数据,以创建具有字段'name' , 'grade'和'age'的3-by-1结构数组:

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 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html) , CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html) , STR2DOUBLE (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/str2double.html)和CELL2STRUCT函数 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cell2struct.html) 。



更多&回答... (https://stackoverflow.com/questions/3048112)