# Reshape matrix with averages of 4 elements in each row

5 views (last 30 days)
Erin on 12 Sep 2022
Commented: Erin on 13 Sep 2022
Hello,
I want to take the average of every 4 elements in each row in A and put that into a smaller matrix B as shown below.
A = [ 0 2 2 4 0 6 4 6
1 1 2 8 0 0 4 0
9 9 2 8 0 0 0 8...]
B = [ 2 4
3 1
7 2...]
Any help is much appreciated, thanks in advance!
##### 2 CommentsShowHide 1 older comment
Erin on 12 Sep 2022
yes

Walter Roberson on 12 Sep 2022
A = [ 0 2 2 4 0 6 4 6
1 1 2 8 0 0 4 0
9 9 2 8 0 0 0 8]
A = 3×8
0 2 2 4 0 6 4 6 1 1 2 8 0 0 4 0 9 9 2 8 0 0 0 8
B = reshape(mean(reshape(A.', 4, []), 1), [], size(A,1)).'
B = 3×2
2 4 3 1 7 2
This is not the most obvious of methods. You first transpose rows and columns so that what were originally the row values become consecutive in memory. You can then reshape into groups of 4 and take the mean along the rows, and then reshape and transpose back.
The above process has the advantage of having the 4 be adjustable to any length that divides the number of columns.
In the specific case of 4, you can instead use
temp = double(A);
B = (temp(:,1:4:end) + temp(:,2:4:end) + temp(:,3:4:end) + temp(:,4:4:end))/4
B = 3×2
2 4 3 1 7 2
The double(A) step is there because A is not necessarily an integer data type. If it were, for example, uint8 (such as an image) and you were to add the values, then you would likely "saturate" the uint8 representation. So you need to do the addition as double (or at least something that is certain to be able to handle the entire possible range of sums) in case it is not already. If you know for sure that A is already double, you can skip the step,
B = (A(:,1:4:end) + A(:,2:4:end) + A(:,3:4:end) + A(:,4:4:end))/4
Erin on 13 Sep 2022
Thank you so much!

the cyclist on 13 Sep 2022
Here is one way:
n = 4;
A = [ 0 2 2 4 0 6 4 6
1 1 2 8 0 0 4 0
9 9 2 8 0 0 0 8];
tmp = movmean(A,[0 n-1],2);
B = tmp(:,1:n:end)
B = 3×2
2 4 3 1 7 2
Erin on 13 Sep 2022
Thank you for this answer as well!

### Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!