alle_meije
alle_meije

Reputation: 2480

mean time signals grouped by label

given a number of signals in a matrix, say m [T x N] and a grouping variable g [ 1 x N ] with a number of labels L < N

is there an efficient, in-place way to compute mean time signals for every label?

A for loop

ml = zeros (T,L)

for i = 1:T
    for j = 1:L
        ml(i,j) = mean ( m(i,find(g==j)) )
    end
end

is a straightforward way to do it, but could there be a faster/cleaner way, possibly using vectorised code? Just to (a) get rid of for-loops and (b) assign m = labelled_means(m, ...) in one go. I read about statarray, but that looks much less efficient even than this for loop.

Upvotes: 0

Views: 60

Answers (3)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

You can use accumarray

[X,Y] = ndgrid(1:size(A,1), g);
accumarray([X(:) Y(:)], A(:), [], @mean);

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112749

You can use arrayfun. It will be cleaner, don't know if faster:

result = arrayfun(@(n) mean(A(:,find(g==n)),2),1:2,'UniformOutput',false);
result = reshape([result{:}],[],L)

For example, with data

A = [1 2 3 4;
     5 6 7 8;
     9 10 11 12];
L = 2;
g = [1 1 2 2];

this gives

result =

    1.5000    3.5000
    5.5000    7.5000
    9.5000   11.5000

Upvotes: 1

Dan
Dan

Reputation: 45752

Well you could get rid of your outer loop really easily:

for j = 1:L
    ml(:,j) = mean(m(:,find(g==j)), 2)
end

Upvotes: 1

Related Questions