I am trying to find the mean
of each adjacent rows in a matrix:
x=
[
1 2 3 4;
2 3 1 0;
1 0 1 0;
3 1 0 1;
]
Simply put,I need a resulting matrix which calculates the mean
of row 1 and 2, and then 3 and 4, which is like the following:
y=
[
2;
0.875
]
How do I go about this?
You can calculate the mean of rows and than the average of two consecutive rows
z=mean(x,2)
z =
2.50000
1.50000
0.50000
1.25000
octave:22> y=((z(1:2:end)+z(2:2:end))/2)
y =
2.00000
0.87500
You can reshape your array and put each other row onto the same row:
octave:6> [n,m] = size(x);
octave:7> mean(reshape(x.', m*2, n/2))
ans =
2.00000 0.87500
Due to the transpose the result is a row vector, you can just transpose it back if you really want to have a column vector.
On new enough MATLAB (that I don't have access to) you should be able to use multiple input arguments for the dimension parameter of mean
, allowing you to utilize multidimensional arrays in this case:
[n,m] = size(x);
mean(reshape(x, [2, n/2, m]), [1, 3]) % should leave n/2-sized dimension
For obvious reasons the above isn't tested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.