how to split an 8x8 2D array

15 views (last 30 days)
Freja
Freja on 10 Aug 2023
Commented: C B on 10 Aug 2023
how would I split an 8x8 2D array into four 4x4 arrays so that I can take the mean of each 4x4 array using the mean function?

Accepted Answer

C B
C B on 10 Aug 2023
Edited: C B on 10 Aug 2023
Is this what you are looking for?
% Sample 8x8 array
A = reshape(1:64, [8,8])
A = 8×8
1 9 17 25 33 41 49 57 2 10 18 26 34 42 50 58 3 11 19 27 35 43 51 59 4 12 20 28 36 44 52 60 5 13 21 29 37 45 53 61 6 14 22 30 38 46 54 62 7 15 23 31 39 47 55 63 8 16 24 32 40 48 56 64
% Splitting into 4x4 arrays
A1 = A(1:4, 1:4)
A1 = 4×4
1 9 17 25 2 10 18 26 3 11 19 27 4 12 20 28
A2 = A(1:4, 5:8)
A2 = 4×4
33 41 49 57 34 42 50 58 35 43 51 59 36 44 52 60
A3 = A(5:8, 1:4)
A3 = 4×4
5 13 21 29 6 14 22 30 7 15 23 31 8 16 24 32
A4 = A(5:8, 5:8)
A4 = 4×4
37 45 53 61 38 46 54 62 39 47 55 63 40 48 56 64
% Computing the mean for each 4x4 array
mean_A1 = mean(A1(:));
mean_A2 = mean(A2(:));
mean_A3 = mean(A3(:));
mean_A4 = mean(A4(:));
% Displaying the results
fprintf('Mean of A1: %f\n', mean_A1);
Mean of A1: 14.500000
fprintf('Mean of A2: %f\n', mean_A2);
Mean of A2: 46.500000
fprintf('Mean of A3: %f\n', mean_A3);
Mean of A3: 18.500000
fprintf('Mean of A4: %f\n', mean_A4);
Mean of A4: 50.500000
  2 Comments
Freja
Freja on 10 Aug 2023
yes thank you! also would there be a way to create a loop to index that and do each calculation for you?
C B
C B on 10 Aug 2023
Yes we can use loop for splitting and Mean calculation
A = reshape(1:64, [8,8]);
mean_values = zeros(1, 4);
% Loop to extract 4x4 matrices and compute mean
for row = 1:2
for col = 1:2
r = (row-1)*4 + 1 : row*4;
c = (col-1)*4 + 1 : col*4;
submatrix = A(r, c);
idx = (row-1)*2 + col;
mean_values(idx) = mean(submatrix(:));
end
end
for i = 1:4
fprintf('Mean of A%d: %f\n', i, mean_values(i));
end
Mean of A1: 14.500000 Mean of A2: 46.500000 Mean of A3: 18.500000 Mean of A4: 50.500000

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!