# Reshape matrix with averages of 4 elements in each row

5 visualizaciones (últimos 30 días)
Erin el 12 de Sept. de 2022
Comentada: Erin el 13 de Sept. de 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 comentariosMostrar NingunoOcultar Ninguno
Torsten el 12 de Sept. de 2022
And the number of columns of A is divisible by 4 ?
Erin el 12 de Sept. de 2022
yes

Iniciar sesión para comentar.

Walter Roberson el 12 de Sept. de 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
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Erin el 13 de Sept. de 2022
Thank you so much!

Iniciar sesión para comentar.

### Más respuestas (1)

the cyclist el 13 de Sept. de 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
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Erin el 13 de Sept. de 2022
Thank you for this answer as well!

Iniciar sesión para comentar.

### Categorías

Más información sobre Logical en Help Center y File Exchange.

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by