Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Average every N rows of column

1,134 views
Skip to first unread message

Randall

unread,
Apr 13, 2012, 10:28:13 AM4/13/12
to
Hello,

I have a simple problem - what is the easiest way to average every 3 rows of a data column of say 141 rows and store that average in a new array of 47 elements?

Thank you!
RB

Sargondjani

unread,
Apr 13, 2012, 2:33:26 PM4/13/12
to
This is relatively easy:
- 'reshape' your column vector in a matrix with 3 rows and ... columns
- take 'mean' of the matrix, which gives you a row vector
- transpose row vector

So:
Avg_3=mean(reshape(A,3,[]))';

I dont know what will happen if the number of columns/3 is not an integer, so you will have to beware of that

ImageAnalyst

unread,
Apr 13, 2012, 3:28:28 PM4/13/12
to
Just for completeness, if you want a sliding mean of 3 columns, do it
like below. Sargondjani's mean "jumps" by 3 everytime. You weren't
specific so I thought I'd give a demo for both ways.

% Create sample data.
A = randi(4, [9,1])

% Calculate mean of 3 rows, then the next 3 rows, etc.
jumping_mean = mean(reshape(A,3,[]))'

% Calculate means of rows 1-3, then of rows 2-4,
% then of rows 3-5, then of rows 4-6, etc.
sliding_mean = conv(A, [1;1;1]/3, 'valid')

Results in command window:

A =
1
2
4
2
3
1
4
2
3
jumping_mean =
2.3333
2.0000
3.0000
sliding_mean =
2.3333
2.6667
3.0000
2.0000
2.6667
2.3333
3.0000

Sargondjani

unread,
Apr 13, 2012, 5:53:28 PM4/13/12
to
he meant the sliding mean, as he vector would contain 141/3=47 elements :-)

by the way, my solution only works for vectors, but i think it is relatively easy to do it for a matrix as well

i think you should reshape your rows into the third dimension, take the mean and reshape the third dimensions back into rows. i think you should be able to figure this out yourself if you want that (you could also do it with a for loop but that will be slower)

ImageAnalyst

unread,
Apr 13, 2012, 6:54:17 PM4/13/12
to
On Apr 13, 5:53 pm, "Sargondjani " <sponsst...@hotmail.com> wrote:
> he meant the sliding mean, as he vector would contain 141/3=47 elements :-)
---------------------------------------------------
I must have not noticed that. I guess he did mean the block-hopping
or jumping mean (whatever you want to call it) like you suggested,
rather than the sliding mean. That can also be done with blockproc(),
which is way over-complicating things in this situation, but is worth
learning for other situations, like when one uses more complicated
operations.

0 new messages