how to calculate the mean using loop
10 次查看(过去 30 天)
显示 更早的评论
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
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
2023-5-25
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')
disp(reshape(meanC, 2,2));
% Validate
Cmean = (A+B)/2
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!