MATLAB Accumarray weighted mean

前端 未结 4 1360
傲寒
傲寒 2020-12-17 02:06

So I am currently using \'accumarray\' to find the averages of a range of numbers wich correspond to matching ID\'s. Ex Input:

ID----Value
1     215
1     33         


        
4条回答
  •  孤街浪徒
    2020-12-17 02:43

    @Naveh - Generally, it is advised to avoid using loops in Matlab. Specifically, if you have a large set of data with many groups - it can be very slow.

    Using accumarrayis the way to go, but defining a function of the indices, as suggested by @chappjc, is error-prone, since in order to be be captured by the anonymous function, you must make sure that

    data is not an input to WeightedMeanFcn. It must be defined before defining WeightedMeanFcn,

    as @chappjc says in his comment.

    A slight modification to overcome this problem is to use accumarray twice:

    Weights = data(:,3); Vals = data(:,2); % pick your columns here    
    app = accumarray(Groups, Weights.*vals, [], @mean)./accumarray(Groups, Weights, [], @mean);
    

    Sometimes you may need to replace the [] argument by the size of the required output.

提交回复
热议问题