如何在 MATLAB 中根据一个字段对结构体数组进行排序?
我之前发布介绍了如何显示和访问结构体数组内容。该档案由州、首府和人口组成。现在,我在通过按字母顺序组织这些状态来创建新结构时遇到了麻烦。我通过 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
我希望我能把自己说清楚。
I previously posted on how to display and access structure array content. The file consisted of states, capitals, and populations. Now I'm having trouble in created a new structure by organizing these states in alphabetical order. I did this by the sortrows
function, and I tried pairing up the values of population and the capitals with the alphabetical states, but I can't seem to get it to be an array. I want it to be an array so I can write it to a file. This is what I have so far:
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
I hope I'm making myself clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此对读入的元胞数组进行排序(无需要转换),然后使用 this< 写入文件/a>.
Use this to sort the cell array read in (no conversion needed), then write to file with this.
关于您的排序问题,函数 SORT 将作为第二个返回输出一个排序索引,可用于将相同的排序顺序应用于其他数组。例如,您可以在创建结构数组之前对数组进行排序:
或者您可以在创建结构数组之后应用排序:
但是,我不确定什么你的意思是当你说“我希望它是一个数组,这样我就可以写入文件”。
With respect to your sorting issue, The function SORT will return as its second output a sort index which can be used to apply the same sort order to other arrays. For example, you could sort your arrays before you create your structure array:
Or you could apply your sorting after you create your structure array:
However, I'm not sure what you mean when you say "I want it to be an array so I can write to a file."