would there be a way to create a loop for splitting an 8x8 array into seperate 4x4 arrays and then find the mean of each of the 4x4 arrays and place each of the mean values into a new array ?

댓글 수: 5

Dyuman Joshi
Dyuman Joshi 2023년 8월 10일
Do you want (fixed) 4 4x4 array, like top left, top right, bottom left and bottom right?
or do you want (sliding) 4x4 arrays like (row 1-4, col 1-4); (row 1-4, col 2-5) and so on?
Stephen23
Stephen23 2023년 8월 10일
편집: Stephen23 2023년 8월 10일
A = reshape(1:64,8,8);
M = mean(permute(reshape(A,4,2,4,2),[2,4,1,3]),3:4)
M = 2×2
14.5000 46.5000 18.5000 50.5000
F = @(s) mean(s.data(:));
M = blockproc(A,[4,4],F)
M = 2×2
14.5000 46.5000 18.5000 50.5000
B = conv2(A,ones(4,4));
M = B(4:4:end,4:4:end)/16
M = 2×2
14.5000 46.5000 18.5000 50.5000
Bruno Luong
Bruno Luong 2023년 8월 10일
편집: Bruno Luong 2023년 8월 10일
No need for permute, squeeze does the job just fine and perhaps faster (no data moving around)
A = reshape(1:64,8,8);
M = squeeze(mean(reshape(A,[4 2 4 2]),[1 3]))
M = 2×2
14.5000 46.5000 18.5000 50.5000
"No need for permute, squeeze does the job just fine"
Not really, because SQUEEZE is fragile, unlike PERMUTE. It all looks "fine" ... until one day the user has data which consists of one row of blocks and are then astonished when the output has the wrong orientation:
A = reshape(1:32,4,8)
A = 4×8
1 5 9 13 17 21 25 29 2 6 10 14 18 22 26 30 3 7 11 15 19 23 27 31 4 8 12 16 20 24 28 32
M = squeeze(mean(reshape(A,[4 1 4 2]),[1 3])) % oops, wrong output
M = 2×1
8.5000 24.5000
M = mean(permute(reshape(A,4,1,4,2),[2,4,1,3]),3:4) % aaah, much better
M = 1×2
8.5000 24.5000
M = permute(mean(reshape(A,4,1,4,2),[1,3]),[2,4,1,3]) % also this
M = 1×2
8.5000 24.5000
SQUEEZE is just like LENGTH: used only by people who like hidden bugs in their code.
Bruno Luong
Bruno Luong 2023년 8월 11일
편집: Bruno Luong 2023년 8월 11일
OP stated clearly he wants average on 8 x 8 matrix not 4 x 8.
But granted if one doesn't like squeeze, in this block average problem use reshape rather than permute for efficienty
A = reshape(1:32,4,8)
A = 4×8
1 5 9 13 17 21 25 29 2 6 10 14 18 22 26 30 3 7 11 15 19 23 27 31 4 8 12 16 20 24 28 32
M = reshape(mean(reshape(A,[4 1 4 2]),[1 3]), [1 2])
M = 1×2
8.5000 24.5000

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

 채택된 답변

Chetan Bhavsar
Chetan Bhavsar 2023년 8월 10일

1 개 추천

I have already answered you same apart from making mean value as new array. here is how you can do it.
A = reshape(1:64, [8,8]);
mean_values = zeros(2,2);
% Loop to extract 4x4 matrices and compute mean
for row = 1:2
for col = 1:2
r_idx = (row-1)*4 + 1 : row*4;
c_idx = (col-1)*4 + 1 : col*4;
submatrix = A(r_idx, c_idx);
mean_values(row, col) = mean(submatrix(:));
end
end
disp(mean_values);
14.5000 46.5000 18.5000 50.5000

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2023년 8월 10일

편집:

2023년 8월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by