Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running mean of a matrix in matlab

Tags:

matlab

Given the nxN matrix A. I want to find the running mean of the rows of the matrix. For this I have done:

mean = cumsum(A, 2);
for k = 1:N
    mean(:, k) = mean(:, k)/k;
end

but for large N this takes a while. Is there a more efficient way to do this in MATLAB?

like image 275
user3701257 Avatar asked Feb 09 '23 09:02

user3701257


1 Answers

Note: zeeMonkeez's solution is fastest according to some rough benchmarks at the end of my post.

How about

N = 1000;
A = rand(N, N);
m = cumsum(A, 2);
m1 = zeros(size(m));
tic
for j = 1:1000;
    for k = 1:N
        m1(:, k) = m(:, k)/k;
    end
end
toc

Elapsed time is 6.971112 seconds.

tic
for j = 1:1000
n = repmat(1:N, N, 1);
m2 = m./n;
end
toc

Elapsed time is 2.471035 seconds.

Here, you transform your problem into a matrix multiplication (instead of dividing element-wise, divide one matrix by the other point-wise). The matrix you would like to divide by looks like this:

[1, 2, 3, ..., N;
 1, 2, .....
 .
 .
 1, 2, ....     ]

which you can get using repmat.

EDIT: BENCHMARK

bsxfun as used by @zeeMonkeez is even faster. Both, for the above case (10% difference on my system) and also for a larger matrix (N = 10000) for which case my version actually performs worst (35 sec, vs 30 from OP and 23 from zeeMonkeez's solution).

like image 57
lhcgeneva Avatar answered Feb 16 '23 01:02

lhcgeneva