【问题标题】:MATLAB: removing non-unique numbers from a field within a structureMATLAB:从结构中的字段中删除非唯一数字
【发布时间】:2016-01-23 00:03:45
【问题描述】:

我在 Matlab 中有一个结构,每个字段都包含具有不同数量变量的元素。我想删除出现在同一字段中的重复数字:我知道 unique() 函数并且知道如何使用它一次扫描一个字段而不是整个字段。

我想我想要这样的东西:

structure(1:length(structure)).field=unique(structure(1:length(structure)).field

然后得到 原创

field=[1,2,3] [1,4,5] [2,5,8]

变成

field=[1,2,3] [4,5] [8]

可能是一个类似于下面的复杂 for 循环(不起作用),它会从字段中的第一个元素中获取值,搜索每个附加元素,如果存在该值,则将其设置为 =[]; ,并以这种方式迭代?

    for n=1:length(RESULTS)
        for m=1:length(RESULTS(n).Volumes)
            for l=1:length(RESULTS)
                for o=1:length(RESULTS(l).Volumes)
                    if RESULTS(n).Volumes(m)==RESULTS(l).Volumes(o)
                        RESULTS(l).Volumes(o)=[];
                    end               
                end
            end
        end
    end

谢谢!

【问题讨论】:

    标签: matlab field structure unique element


    【解决方案1】:

    这是一个快速而肮脏的尝试,但您也许可以改进它。假设您的结构数组和字段是sa(:).v。我还假设该字段包含一个 1xn 数字数组,如您的示例所示。首先,用所有字段值的连接创建一个“联合”数组并过滤非唯一值:

    joint = cell2mat({sa.v});    
    [uniqJoint,~,backIdx] = unique(joint);
    

    “uniqJoint”数组也已排序,但“backIdx”数组包含索引,如果应用于 uniqJoint,将重建原始“joint”数组。我们需要以某种方式将它们与原始索引 (i,j) 连接到结构数组和字段值sa(i).v(j) 中。为此,我尝试创建一个与“joint”大小相同的数组,其中包含最初在“joint”数组中具有相应元素的结构的索引:

    saIdx = cell2mat(arrayfun(@(i) i * ones(1,length(sa(i).v)), ...
                     1:length(sa), 'UniformOutput', false));
    

    然后您可以编辑(或者,在我的情况下,复制和修改其副本)结构数组,以将字段设置为以前未出现过的值。为此,我保留了一个逻辑数组来将“backIdx”的索引标记为“已使用”,在这种情况下,我会在重建每个结构的字段时跳过这些值:

    sb = sa;
    used = false(length(backIdx));
    for i = 1:length(sa)
      origInd = find(saIdx == i); % Which indices into backIdx correspond to this struct?
      newInd = []; % Which indices will be used?
      for curI = backIdx(origInd)
        if ~used(curI)
          % Mark as used and add to the "to copy" list
          used(curI) = true;
          newInd(end+1) = curI;
        end
      end
      % Rewrite the field with only the indices that were not used before
      sb(i).v = uniqJoint(newInd);
    end
    

    最后,sb(i).v 中的数据包含与sa(i).v 相同的数字,没有重复,并删除了出现在结构的任何先前元素中的数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多