2011-05-20 142 views
0

previously posted如何顯示和訪問結構陣列內容上。該文件由國家,首都和人口組成。現在,我通過按字母順序組織這些州來創建新結構方面遇到了麻煩。我這樣做是由sortrows功能,我嘗試配對了人口的價值觀和首都與字母的狀態,但我似乎無法得到它是一個數組。我希望它是一個數組,所以我可以將它寫入一個文件。這是我迄今爲止:如何基於MATLAB中的一個字段對結構數組進行排序?

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 

我希望我讓自己清楚。

回答

0

使用this來排序讀入的單元陣列(不需要轉換),然後寫入文件this

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); 

不過,我當你說「我希望它是一個數組,因此我可以寫入一個文件」時,m不確定你的意思。

相關問題