Search code examples
matlabmatrixvectorizationadjacency-matrix

An efficient way for creating an empirical joint probability matrix by summing rows of samples according to a specified order in matlab


Lets say I have a samples matrix samples (n_samples x n1) and a labels vector labels (n_samples x 1), where the labels are in the range [1:n2]

I am looking for an efficient way to create an empirical joint probability matrix P in the size n2 x n1. Where for every sample i, we add its row samples(i, :) to P in the location indicated by labels(i).

I.e. (pseudo code)

for i = 1:n_samples
   P(l(i), :) += M(i, :)

Is there a killer matlab command for doing that? Rather than a for loop or arrayfun?


Solution

  • Following @BillBokeey comment: Here is the solution

    [xx, yy] = ndgrid(labels,1:size(samples,2));
    P = accumarray([xx(:) yy(:)],samples(:));