【问题标题】:Matlab: Sort 2 cell matrices of stringsMatlab:对字符串的2个单元格矩阵进行排序
【发布时间】:2015-05-07 09:02:21
【问题描述】:

我有 2 个字符串单元矩阵,我想比较和排序。例如:

Data1={'hello','daddy','mama';'0','55','60';'asd','','dwadsdwa'};

Data2={'cat','daddy','dog','cat','mama','daddy';'21','54','79','1','0','231';'sa','wda','thjd','gf','wda','sda'};

我想比较矩阵的第一行并使用匹配的元素及其列创建一个新的结果矩阵。喜欢:

matches={'daddy','daddy','daddy','mama','mama';'55','54','231','60','0';'','wda','sda','dwadsdwa','wda'};

我试过了:

Da1Index=find(ismember(Data1(1,:),Data2(1,:)));
Firstmatches=Data1(:,Da1Index);

Da2Index=find(ismember(Data2(1,:),Data1(1,:)));
Secondmatches=Data2(:,Da2Index);

所以我会在其他 2 个 Cell 矩阵中获得匹配的元素及其列。现在我可以在 Secondmatches 单元格数组中搜索 Firstmatches 的每个名称元素,但我想知道是否有更好的方法? 另外我不知道如何将列添加到正确的位置。

也许有更简单的方法可以做到这一点?我希望很清楚我想要实现的目标!

【问题讨论】:

    标签: string matlab cell


    【解决方案1】:

    你可以这样做:

    i1 = ismember(Data1(1,:), Data2(1,:));  %// columns of Data1 to keep
    i2 = ismember(Data2(1,:), Data1(1,:));  %// columns of Data1 to keep
    matches = [Data1(:,i1) Data2(:,i2)];    %// build result
    matches = sortrows(matches.').';        %// sort if needed. Note: lexicographical order
    

    【讨论】:

    • 非常感谢,这非常有效。但是你能解释一下 sortrows(matches.').';表达?什么是 。')。'在做什么?
    • .'是转置。 sortrows 对数组的行进行排序,但您想要对列进行排序。所以你转置,对行进行排序,然后转回
    猜你喜欢
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多