0

之前发布了关于如何显示和访问结构数组内容的文章。该文件由州、首府和人口组成。现在,我无法通过按字母顺序组织这些状态来创建新结构。我通过sortrows函数做到了这一点,我尝试将人口和大写字母的值与字母状态配对,但我似乎无法让它成为一个数组。我希望它是一个数组,所以我可以将它写入文件。这是我到目前为止所拥有的:

    fid=fopen('Regions_list.txt')
    file=textscan(fid,'%s %s %f','delimiter',',')
    State=file{1}
    Capital=file{2}
    Population=num2cell(file{3})

sortedStates=sortrows(State)
    n=length(State)

    regions=struct('State',State,...
    'Capital',Capital,...
    'Population',Population)

for k=1:n;
 region=sortedStates(k);
 state_name={regions.State};
 state_reference=strcmpi(state_name,region);
 state_info=regions(state_reference)
end

我希望我清楚自己。

4

2 回答 2

0

使用它对读入的元胞数组进行排序(无需转换),然后使用this写入文件

于 2011-05-22T04:59:37.880 回答
0

关于您的排序问题,函数SORT将作为其第二个输出返回一个排序索引,该索引可用于将相同的排序顺序应用于其他数组。例如,您可以在创建结构数组之前对数组进行排序:

[sortedStates,sortIndex] = sort(State);
regions = struct('State',sortedStates,...
                 'Capital',Capital(sortIndex),...
                 'Population',Population(sortIndex));

或者,您可以在创建结构数组应用排序:

regions = struct('State',State,...
                 'Capital',Capital,...
                 'Population',Population);
[~,sortIndex] = sort({regions.State});
regions = regions(sortIndex);

但是,当您说“我希望它是一个数组以便我可以写入文件”时,我不确定您的意思。

于 2011-05-23T14:09:38.100 回答