想象一下,f1列和f2列是一个称为inputStruct的结构,f3列和f4列是另一个名为outputStruct的结构(对不起,格式化不好)。我想按照inputStruct.f2的升序对inputStruct中的所有字段进行排序,以便输出为outputStruct(f3和f4列)。我将如何处理?
f1_f2 | f3_f4
a__4 | c__1
b__2 | b__2
c__1 | e__3
d__5 | a__4
e__3 | d__5
答案 0 :(得分:2)
使用sort
获得outputStruct.f4
和相应的索引。使用这些索引重新排列inputStruct.f1
并获得outputStruct.f3
。
[outputStruct.f4, ind] = sort(inputStruct.f2);
outputStruct.f3 = inputStruct.f1(ind);
或对于多个字段,只需遍历所有字段:
[~, ind] = sort(inputStruct.f2); %Sorting according to field f2
fns = fieldnames(inputStruct); %Retrieving the names of all the fields
for k = 1:numel(fns) %Looping for each field
outputStruct.(fns{k}) = inputStruct.(fns{k})(ind);
end
%Note: This creates outputStruct with the same fields as that of inputStruct
%but that can be adjusted if needed