Reshape matrix with averages of 4 elements in each row

조회 수: 5 (최근 30일)
Erin
Erin 2022년 9월 12일
댓글: Erin 2022년 9월 13일
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
Torsten
Torsten 2022년 9월 12일
And the number of columns of A is divisible by 4 ?

댓글을 달려면 로그인하십시오.

채택된 답변

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