Reshape matrix with averages of 4 elements in each row

6 次查看(过去 30 天)
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!

采纳的回答

Walter Roberson
Walter Roberson 2022-9-12
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 个)

the cyclist
the cyclist 2022-9-13
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by