How to calculate averages for each rows from a specific column to a specific column in a matrix?
2 views (last 30 days)
Show older comments
Roland Baczur
on 5 Apr 2017
Commented: Roland Baczur
on 5 Apr 2017
So, I have a large matrix (rows = 1000; columns = 1000) and I have to compute the averages of each rows, but not the whole, only 100 columns, each step.
Let me explain:
There is a given matrix.
A =
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36
In this case, I have to take the average of 2 columns (step by step) in each rows:
(1+2)/2 (3+4)/2 (5+6)/2
(7+8)/2 (9+10)/2 (11+12)/2
(13+14)/2 (15+16)/2 (17+18)/2
...
The solution is a new matrix:
B =
1,5 3,5 5,5
7,5 9,5 11,5
13,5 15,5 17,5
19,5 21,5 23,5
25,5 27,5 29,5
31,5 33,5 35,5
How can I code this to make the same results in bigger sizes (to calculate the average in each row by columns 1-100; 101-200; 201-300; etc...)?
Any idea is highly welcomend!
Thank you!
0 Comments
Accepted Answer
the cyclist
on 5 Apr 2017
A = ...
[1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36];
NC = 2; % This is the number of columns you want to average over.
tmp = movmean(A,NC,2); % Note that the "2" here is dimension to average over, NOT the number of columns
B = tmp(:,NC:NC:end);
More Answers (1)
Jan
on 5 Apr 2017
Edited: Jan
on 5 Apr 2017
A = [1 2 3 4 5 6; ...
7 8 9 10 11 12; ...
13 14 15 16 17 18; ...
19 20 21 22 23 24; ...
25 26 27 28 29 30; ...
31 32 33 34 35 36];
sA = size(A);
AA = reshape(A, [sA(1), 2, sA(2)/2]);
Am = squeeze(sum(AA, 2) / 2);
In the general case the size of A might not be a multiple of the block width. Then see FEX: BlockMean: Create the mean over N columns:
S = size(A);
Sf = S(2) - mod(S(2), N); % Crop trailing columns
Nv = Sf / N;
AA = reshape(A(:, 1:Sf), S(1), N, Nv);
Am = sum(AA, 2) .* (1.0 / N);
Am = reshape(Am, S(1), Nv);
See Also
Categories
Find more on Array and Matrix Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!