首先,我让用户输入他们自己的文本文件,其中包含州、首都和人口,然后我使用以下代码将所有这些值放入结构数组中:
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);
我的第一个问题:是否可以显示结构中的所有值?显示结构数组只是给我这个:
50x1 struct array with fields:
State
Capital
Population
我的第二个问题:我是否可以通过尝试仅查找例如 'California'
来访问此结构中的信息?
最佳答案
正如您已经发现的那样,MATLAB 中结构体数组的默认显示并没有告诉您太多信息,只是告诉您数组维数和字段名称。如果您想查看内容,则必须自己创建格式化输出。一种方法是使用 STRUCT2CELL收集元胞数组中的结构内容,然后使用 FPRINTF以特定格式显示单元格内容。这是一个例子:
>> regions = struct('State',{'New York'; 'Ohio'; 'North Carolina'},...
'Capital',{'Albany'; 'Columbus'; 'Raleigh'},...
'Population',{97856; 787033; 403892}); %# Sample structure
>> cellData = struct2cell(regions); %# A 3-by-3 cell array
>> fprintf('%15s (%s): %d\n',cellData{:}); %# Print the data
New York (Albany): 97856
Ohio (Columbus): 787033
North Carolina (Raleigh): 403892
关于您的第二个问题,您可以从元胞数组中的 'State'
字段中收集条目,将它们与给定的名称进行比较 STRCMP得到 logical index ,然后得到对应的结构体数组元素:
>> stateNames = {regions.State}; %# A 1-by-3 cell array of names
>> stateIndex = strcmp(stateNames,'Ohio'); %# Find the index for `Ohio`
>> stateData = regions(stateIndex) %# Get the array element for `Ohio`
stateData =
State: 'Ohio'
Capital: 'Columbus'
Population: 787033
注意:
正如您在评论中提到的,结构数组中的每个 'Population'
条目最终都包含人口数据的整个 50×1 向量。这可能是因为您的示例代码中的 file{3}
包含一个vector,而 file{1}
和 文件{2}
包含元胞数组。为了在结构数组的元素之间正确分布 file{3}
中的向量内容,您需要分解向量并将每个值放在元胞数组的单独元胞中,使用NUM2CELL在将其传递给 STRUCT 之前.像这样定义 Population
应该可以解决问题:
Population = num2cell(file{3});
关于arrays - 如何在 MATLAB 中显示和访问结构数组内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6052145/