2011-07-02 59 views
2

編寫一個函數sortStruct,它接收結構數組 ,然後用輸入字段中的值對結構數組排序。 如果這些值是數字,則函數將它們從最低排序到最高排列爲 。如果值是字符,則函數按字母順序排列 單詞(例如「蘋果」在 「蘋果」之前)。如果該字段不存在於結構數組中,則函數返回字符串'Invalid Field Name'。如何在不知道字段數量的情況下更改結構中每個字段值的順序? (MatLab)

這是我到目前爲止有:

function [ structsort ] = sortStruct(strucArray, fname) 

if isfield(strucArray, fname) ~= '1' 
    structsort = 'Invalid Field Name'; 
end 

i = class(fname); 

for i = 'double' 
    [sorteddoub inddoub] = sort(fname); 
    fieldn = fieldnames(strucArray); 
    num = length(fieldn); 
    strucArray = setfield(strucArray, fname, sorteddoub); 

    structsort = setfield(strucArray, fieldn, fieldn(inddoub)); 
end 

for i = 'char' 
    [sortedchar indchar] = sort(char2num(fname(1))); 
end 
+0

任何指針將是巨大的。謝謝! –

回答

2

你似乎是在正確的軌道上,除了從語法錯誤。因此幾點意見:

  • ISFIELD返回真/假
  • 一種更好的方式來測試變量使用的數據類型是**系列的功能:ISNUMERICISSTRUCTISCHAR,...
  • 您應該閱讀if/for/...構造
  • SORT函數可以處理數字和單元格數組的字符串的區別。您應該使用的功能(閱讀文檔頁面第一)
  • 訪問結構字段的語法動態是:structName.(dynamicExpression)

話雖如此,這裏是我怎麼會寫這樣的功能:

function structSorted = sortStruct(structArray, fname) 
    if ~isfield(structArray,fname) 
     error('Invalid Field Name') 
    end 

    if isnumeric(structArray(1).(fname)) 
     data = [structArray.(fname)]; 
    else 
     data = {structArray.(fname)}; 
    end 

    [~,order] = sort(data); 
    structSorted = structArray(order); 
end 

並讓與結構的一些隨機陣列測試函數:

%# lets build some array of structures 
chars = char(97:122); 
str = cellstr(chars(ceil(numel(chars).*rand(10,6)))); 
[s(1:10).str] = str{:}; 
num = num2cell(rand(10,1)); 
[s(1:10).num] = num{:}; 

%# sort according to a field 
s_str = sortStruct(s, 'str'); 
s_num = sortStruct(s, 'num'); 
%#s_err = sortStruct(s, 'zzzzz'); 

%# compare the two sorted array of structures 
myS2C = @(s) squeeze(struct2cell(s))'; %'# a helper function to show results 
myS2C(s_str) 
myS2C(s_num) 

由場排序給:

>> myS2C(s_str) 
ans = 
    'cbawoj' [ 0.10401] 
    'fqwiek' [ 0.17567] 
    'fskvdc' [ 0.46847] 
    'hezhbh' [ 0.33585] 
    'kyeaxv' [ 0.67539] 
    'ooumrm' [ 0.20895] 
    'qbnqit' [ 0.90515] 
    'wcwyjs' [0.056705] 
    'wdyhlz' [ 0.52189] 
    'ytdoze' [ 0.91213] 

而排序由現場num

>> myS2C(s_num) 
ans = 
    'wcwyjs' [0.056705] 
    'cbawoj' [ 0.10401] 
    'fqwiek' [ 0.17567] 
    'ooumrm' [ 0.20895] 
    'hezhbh' [ 0.33585] 
    'fskvdc' [ 0.46847] 
    'wdyhlz' [ 0.52189] 
    'kyeaxv' [ 0.67539] 
    'qbnqit' [ 0.90515] 
    'ytdoze' [ 0.91213] 
相關問題