【问题标题】:Finding the max number of a column in MATLAB, which allocates to a specific string在 MATLAB 中查找分配给特定字符串的最大列数
【发布时间】:2018-02-20 20:59:40
【问题描述】:

假设我在 MATLAB 中有一个这种类型的表:

Location     String      Number

1              a           26 
1              b           361  
2              c           28
2              a           45 
3              a           78
4              b           82

我想创建一个只返回 3 行的脚本,其中包含每个字符串的最大数字。所以在这种情况下,返回的表如下:

Location    String     Number

3            a         78
1            b         361   
2            c         28

我想要处理的实际表要大得多,尽管为了简单起见我这样写。关于如何解决此任务的任何想法?提前感谢您的宝贵时间!

【问题讨论】:

    标签: matlab


    【解决方案1】:

    您可以使用splitapply,每行使用id。 详情请看cmets...

    % Assign unique ID to each row
    tbl.id = (1:size(tbl,1))';
    % Get groups of the different strings
    g = findgroups(tbl.String);
    % create function which gets id of max within each group 
    % f must take arguments corresponding to each splitapply table column
    f = @(num,id) id(find(num == max(num), 1));
    % Use splitapply to apply the function f to all different groups
    idx = splitapply( f, tbl(:,{'Number','id'}), g );
    % Collect rows
    outTbl = tbl(idx, {'Location', 'String', 'Number'});
    
    >> outTbl = 
       Location   String    Number
          3        'a'        78   
          1        'b'       361   
          2        'c'        28   
    

    或者只是一个简单的循环。此循环仅针对 String 的唯一值,因此应该很快。

    u = unique(tbl.String);
    c = cell(numel(u), size(tbl,2));
    for ii = 1:numel(u)
        temp = tbl(strcmp(tbl.String, u{ii}),:);
        [~, idx] = max(temp.Number);
        c(ii,:) = table2cell(temp(idx,:));
    end
    outTbl = cell2table(c, 'VariableNames', tbl.Properties.VariableNames);
    

    【讨论】:

      【解决方案2】:

      找到我的想法是每个字符串的最大值。

      创建一个包含所有字符串的向量,并且只包含一次。比如:

      strs=['a','b','c'];

      然后创建一个向量来存储每个字符串的最大值:

      n=length(strs);
      max_values=zeros(1,n);
      

      现在用整个数据的大小创建一个循环来比较当前的 max_value 和当前值并替换 if current_value>max_value:

      for i=1:your_table_size
         m=find(strs==current_table_string);   % This finds the index of max_values
         if max_values(m)<current_table_Number   % This the the i_th row table_number
            max_values(m)=current_table_Number;
         end
      end
      

      【讨论】:

      • 这不会输出 OP 要求的内容,即每个类别的所有最大行数的表。相反,它只是输出每个类别的所有最大值的向量。
      • 感谢您的评论@Wolfie。我主要是指出寻找所需内容的想法,正如您所见,我并没有编写整个脚本。因此,是的,你是对的,但我相信用表格参数替换代码对于 OP 来说并不是一项艰巨的任务,只要他明白这一点。
      猜你喜欢
      • 2014-02-14
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多