编写一个名为
sortStruct
的函数,它接受一个结构数组 然后通过输入字段中的值对结构数组进行排序。 如果值是数字,则函数将它们从最低值排序到 最高。如果值是字符,则函数对其进行排序 单词按字母顺序排列,与案例有关(例如“苹果”之前 '苹果')。如果结构数组中不存在该字段,那么 function返回字符串'Invalid Field Name'。
这是我到目前为止所做的:
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
返回true / false ISNUMERIC
,ISSTRUCT
,ISCHAR
,... if
/ for
/ ... constructs 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)
按字段str
排序:
>> 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]