【问题标题】:How to sort structure arrays in MATLAB?如何在 MATLAB 中对结构体数组进行排序?
【发布时间】:2009-09-30 11:12:46
【问题描述】:

我正在使用 MATLAB 中使用颜色直方图交集的图像检索系统。此方法为我提供以下数据:表示直方图相交距离的实数和图像文件名。因为它们是不同的数据类型,所以我将它们存储在包含两个字段的结构体数组中,然后将此结构体保存在 .mat 文件中。现在我需要根据直方图相交距离降序对这个结构进行排序,以便检索具有最高直方图相交距离的图像。我尝试了很多方法来对这些数据进行排序,但没有结果。请问你能帮我解决这个问题吗?

【问题讨论】:

    标签: arrays matlab sorting matlab-struct


    【解决方案1】:

    也可以对整个结构进行排序。

    以 gnovice 的示例为基础...

    % Create a structure array
    s = struct('value',{1 7 4},'file',{'img1.jpg' 'img2.jpg' 'img3.jpg'});
    
    % Sort the structure according to values in descending order
    % We are only interested in the second output from the sort command
    
    [blah, order] = sort([s(:).value],'descend');
    
    % Save the sorted output
    
    sortedStruct = s(order);
    

    【讨论】:

    • 注意:要按文件名(或任何字符串)排序,您可以使用[~, order] = sort({s.file});,然后是sortedStruct = s(order);。在这种情况下,您不能使用'descend',直到在将来的某个 Matlab 版本中实现。
    【解决方案2】:

    这里有一个例子说明如何做到这一点,使用函数MAX 而不必排序:

    %# First, create a sample structure array:
    
    s = struct('value',{1 7 4},'file',{'img1.jpg' 'img2.jpg' 'img3.jpg'});
    
    %# Next concatenate the "value" fields and find the index of the maximum value:
    
    [maxValue,index] = max([s.value]);
    
    %# Finally, get the file corresponding to the maximum value:
    
    maxFile = s(index).file;
    

    编辑:如果您想获得 N 个最高值,而不仅仅是最大值,您可以使用 SORT 而不是 MAX (as Shaka suggested)。例如(使用上述结构):

    >> N = 2;  %# Get two highest values
    >> [values,index] = sort([s.value],'descend');  %# Sort all values, largest first
    >> topNFiles = {s(index(1:N)).file}  %# Get N files with the largest values
    
    topNFiles = 
    
        'img2.jpg'    'img3.jpg'
    

    【讨论】:

    • 您也可以使用 cat(1,s.value) 连接值
    • 非常感谢您的回复,我会尝试使用这个功能。请让我获取您的电子邮件地址,以便将我的 matlab cod 发送给您,谢谢
    • @zenab:我的电子邮件地址在我的个人资料中。如果您有任何想直接讨论的内容,请随时给我留言。
    • 您好 gnovice 先生,我想对您的帮助表示衷心的感谢和感谢...我应用了您的解决方案(因为我的结构非常大)它可以有效地工作 Zenab
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 2019-11-27
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多