MATLAB find and apply function to values of repeated indices

前端 未结 4 1867
遇见更好的自我
遇见更好的自我 2020-12-02 03:07

I have a 352x11 matrix, indexed by column 1 with 10 data points. Some of the index values are repeated. I\'d like to find the repeated indices and calculate the mean data po

4条回答
  •  無奈伤痛
    2020-12-02 03:39

    Given you input

    x = [ ...
        26   77.5700   17.9735   32.7200; ...
        27   40.5887   16.6100   31.5800; ...
        28   60.4734   18.5397   33.6200; ...
        28   35.6484   27.2000   54.8000; ...
        29   95.3448   19.0000   37.7300; ...
        30   82.7273   30.4394   39.1400];
    

    You can create an array of indexes where duplicated vgalues share the same index, using the third output of unique.

    %Get index of unique values (1 - N)
    [~, ~, ix] = unique(x(:,1))
    

    Then you can use this array to rebuild your matrix, combining duplicated values with the function of your choice.

    %Use accumarry to rebuild the matrix one column at a time
    result = [...
        accumarray( ix, x(:,1), [], @max )  ...  %Many functions works here, as all inputs are the same.  E.G.  @mean, @max, @min
        accumarray( ix, x(:,2), [], @mean ) ...  %Use mean to combine data, per problem statement.
        accumarray( ix, x(:,3), [], @mean ) ...
        accumarray( ix, x(:,4), [], @mean ) ...
        ]
    

提交回复
热议问题