Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我有一个文本文件,想将其导入到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 : 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 , CELLFUN , STR2DOUBLE和CELL2STRUCT函数 。 更多&回答... |
![]() |
![]() |