正如您已经发现的那样,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 x 1的人口数据向量.这可能是由于示例代码中的文件{3}包含向量,而文件{1}和文件{2}包含单元格数组.为了将文件{3}中的向量内容正确地分布在结构数组的元素之间,您需要先断开向量并使用NUM2CELL将每个值放在单元格数组的单独单元格中,然后再将其传递给STRUCT.像这样定义人口应该可以解决问题:
Population = num2cell(file{3});