how to calculate the mean using loop

10 次查看(过去 30 天)
Jincy
Jincy 2023-5-25
评论: Jincy 2023-5-28
i want to calculate the mean value in 2*2 size by creating a loop
A = [1 2; 3 4]; % Matrix A
B = [2 3; 5 6]; % Matrix B
C = [A, B]; % Concatenated matrix C
meanC = 0; % Initialize mean variable
count = 0; % Initialize count variable
Iterate over the 2x2 submatrix of C
for i = 1:2
for j = 1:2
meanC = meanC + C(i, j); % Accumulate the sum
count = count + 1; % Increment the count
end
end
meanC = meanC / count; % Calculate the mean
disp(['Mean of C (2x2):', num2str(meanC)]);
when i am using this code it not giving 2*2 sized mean output
  2 个评论
Walter Roberson
Walter Roberson 2023-5-25
Your code is building a 2 x 4 matrix and totalling all of the entries in that 2 x 4 matrix.
If you are wanting a 2 x 2 output, that suggests that you want the mean of A(1,1) with B(1,1), and A(1,2) with B(1,2) and so on. Which would be just (A+B)/2 ... unless you are expected build a function that takes an indefinite number of matrix inputs.

请先登录,再进行评论。

回答(1 个)

Sulaymon Eshkabilov
If I understood your question correctly, here is how it can be done:
A = [1 2; 3 4]; % Matrix A
B = [2 3; 5 6]; % Matrix B
meanC = 0; % Initialize mean variable
count = 2; % Initialize count variable
%Iterate over the 2x2 submatrix of C
for i = 1:2
for j = 1:2
meanC(i,j) = A(i, j)+B(i,j); % Accumulate the sum
end
end
meanC = meanC / count; % Calculate the mean
fprintf('Mean of C (2x2): \n')
Mean of C (2x2):
disp(reshape(meanC, 2,2));
1.5000 2.5000 4.0000 5.0000
% Validate
Cmean = (A+B)/2
Cmean = 2×2
1.5000 2.5000 4.0000 5.0000

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by