フィルターのクリア

how to calculate the mean using loop

25 ビュー (過去 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.
Jincy
Jincy 2023 年 5 月 28 日
Thank you

サインインしてコメントする。

回答 (1 件)

Sulaymon Eshkabilov
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')
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
  1 件のコメント
Jincy
Jincy 2023 年 5 月 28 日
Thanku you

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by