【问题标题】:How can I display and access structure array contents in MATLAB?如何在 MATLAB 中显示和访问结构体数组内容?
【发布时间】:2011-05-18 23:20:39
【问题描述】:

首先,我让用户输入他们自己的包含州、首都和人口的文本文件,然后我使用以下代码将所有这些值放入结构数组中:

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' 来访问此结构中的信息?

【问题讨论】:

标签: arrays matlab matlab-struct


【解决方案1】:

正如您已经发现的那样,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} 包含一个向量,而file{1}file{2} 包含元胞数组。为了将file{3} 中向量的内容正确分布到结构数组的元素中,您需要将向量分解并使用NUM2CELL 将每个值放在单元格数组的单独单元格中,然后再将其传递给@ 987654326@。像这样定义Population应该可以解决问题:

Population = num2cell(file{3});

【讨论】:

  • 对于显示结构的第一部分,我不断收到错误“未为'单元'输入定义函数。”发生这种情况时,我首先想到的是我没有在 fprintf 命令中正确标记 %s 和 %d
  • 我想我可能已经找到了问题,但我可以弄清楚如何解决它,当我输入 region.Population 以查看答案如何出现时,它给了我一个 50x1 数组,其中包含每个州的所有人口......所以单元格数组显示例如'Massachusetts''Boston' [50x1 int32]
  • 我想我可能已经找到了问题,但我可以弄清楚如何解决它,当我输入 region.Population 以查看答案如何出现时,它给了我一个 50x1 数组,其中包含每个州的所有人口......所以单元格数组显示例如'Massachusetts''Boston' [50x1 int32]
  • @Nick:我更新了我的答案以解决您错误的可能来源。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多