The average value of the matrix in the matrix

Given the matrix nxN A. I want to find the current row average of the row. For this, I did:

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

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

+4
source share
2 answers

Note. The zeeMonkeez solution is executed most quickly by some rough criteria at the end of my post.

What 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

The 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 turn your problem into matrix multiplication (instead of dividing the wise element, divide one matrix into another differently). The matrix you want to split is as follows:

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

repmat.

EDIT: BENCHMARK

bsxfun, @zeeMonkeez, . , , ( 10% ), (N = 10000), (35 , 30 OP 23 zeeMonkeez).

+5

bsxfun :

N = 1000;
A = rand(N, N);
m = cumsum(A, 2);

tic
for j = 1:1000;
    m2 = bsxfun(@rdivide, m, 1:N);
end
toc

: 1.555507 .

bsxfun repmat.

+3

Source: https://habr.com/ru/post/1618713/


All Articles