【问题标题】:Comparing two columns and summing the values in Matlab比较两列并对Matlab中的值求和
【发布时间】:2018-07-04 12:52:25
【问题描述】:

我有 2 列这样的:

0.0    1.2
0.0    2.3
0.0    1.5
0.1    1.0
0.1    1.2
0.1    1.4
0.1    1.7
0.4    1.1
0.4    1.3
0.4    1.5

在第 1 列中,0.0 重复 3 次。我想总结相应的元素 (1.2 + 2.3 + 1.5) 在第二列。同样,0.1在第1次重复4次 柱子。我想在第二个中总结相应的元素(1.0 + 1.2 + 1.4 + 1.7) 列等等。

我正在尝试这样

for i = 1:length(col1)
    for j = 1:length(col2)
        % if col2(j) == col1(i)
        % to do
        end
    end
end

【问题讨论】:

    标签: arrays matlab


    【解决方案1】:

    这是uniqueaccumarray 的经典用法:

    x = [0.0    1.2
         0.0    2.3
         0.0    1.5
         0.1    1.0
         0.1    1.2
         0.1    1.4
         0.1    1.7
         0.4    1.1
         0.4    1.3
         0.4    1.5]; % data
    [~, ~, w] = unique(x(:,1)); % labels of unique elements
    result = accumarray(w, x(:,2)); % sum using the above as grouping variable
    

    您也可以使用较新的splitapply 函数代替accumarray

    [~, ~, w] = unique(x(:,1)); % labels of unique elements
    result = splitapply(@sum, x(:,2), w); % sum using the above as grouping variable
    

    【讨论】:

      【解决方案2】:
      a=[0.0    1.2
      0.0    2.3
      0.0    1.5
      0.1    1.0
      0.1    1.2
      0.1    1.4
      0.1    1.7
      0.4    1.1
      0.4    1.3
      0.4    1.5]
      % Get unique col1 values, and indices
      [uniq,~,ib]=unique(a(:,1));
      
      % for each unique value in col1
      for ii=1:length(uniq)
          % sum all col2 values that correspond to the current index of the unique value
          s(ii)=sum(a(ib==ii,2));
      end
      

      给予:

      s =
      
          5.0000    5.3000    3.9000
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多