Reshape matrix with averages of 4 elements in each row

5 vues (au cours des 30 derniers jours)
Erin
Erin le 12 Sep 2022
Commenté : Erin le 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...]
I am pretty new to MatLab, any ideas how I can go about this?
Any help is much appreciated, thanks in advance!
  2 commentaires
Torsten
Torsten le 12 Sep 2022
And the number of columns of A is divisible by 4 ?
Erin
Erin le 12 Sep 2022
yes

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 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

Plus de réponses (1)

the cyclist
the cyclist le 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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by