如何在 Matlab 中对结构中字段的值进行排序?

How to sort values of a field in a structure in Matlab?

在我的代码中,我有一个结构,在它的一个字段中,我想对其值进行排序。 例如,在File_Neg.name的字段中有以下值,应将它们排序为正确的值。

File_Neg.name        --> Sorted File_Neg.name
'-10.000000.dcm'         '-10.000000.dcm'
'-102.500000.dcm'        '-12.500000.dcm'
'-100.000000.dcm'        '-100.000000.dcm' 
'-107.500000.dcm'        '-102.500000.dcm'  
'-112.500000.dcm'        '-107.500000.dcm'
'-110.000000.dcm         '-110.000000.dcm' 
'-12.500000.dcm'         '-112.500000.dcm'    

有一个文件夹,里面有一些带有负标签的图片(上面的例子是图片的标签)。我想以与文件夹中相同的顺序获取它们(这意味着 Sorted File_Neg.name)。但是当 运行 以下代码加载 Files_Neg.name 的值时如上例(左:File_Neg.name),而我想要正确的形式。 我也看到了 this and that 但他们没有帮助我。
如何在 Matlab 中对结构中字段的值进行排序?

Files_Neg = dir('D:\Rename-RealN'); 
File_Neg = dir(strcat('D:\Rename-RealN\', Files_Neg.name, '\', '*.dcm'));  
% when running the code the values of Files_Neg.name load as the above example (left: File_Neg.name)

File_Neg.name:

This answer OP 中链接的问题之一对于 OP 中的问题几乎是正确的。有两个问题:

第一个问题是答案假定标量值包含在要排序的字段中,而在 OP 中,值是字符数组(即老式字符串)。

可以通过将 'UniformOutput',false 添加到 arrayfun 调用来解决此问题:

File_Neg = struct('name',{'-10.000000.dcm','-102.500000.dcm','-100.000000.dcm','-107.500000.dcm','-112.500000.dcm','-110.000000.dcm','-12.500000.dcm'},...
                  'folder',{'a','b','c','d','e1','e2','e3'});

[~,I] = sort(arrayfun(@(x)x.name,File_Neg,'UniformOutput',false));
File_Neg = File_Neg(I);

File_Neg现在根据字典排序(使用ASCII字母排序,意思是大写字母在前,110仍然在12之前)。

第二个问题是OP想按照文件名中数字的大小排序,而不是字典排序。这可以通过提取使用 arrayfun 应用的匿名函数中的值来解决。我们在文件名上使用 str2double,减去最后 4 个字符 '.dcm':

[~,I] = sort(arrayfun(@(x)abs(str2double(x.name(1:end-4))),File_Neg));
File_Neg = File_Neg(I);

有趣的是,我们不想再使用 'UniformOutput',false,因为匿名函数现在 returns 是一个标量值。