Filter löschen
Filter löschen

how to calculate the mean using loop

25 Ansichten (letzte 30 Tage)
Jincy
Jincy am 25 Mai 2023
Kommentiert: Jincy am 28 Mai 2023
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 Kommentare
Walter Roberson
Walter Roberson am 25 Mai 2023
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 am 28 Mai 2023
Thank you

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov am 25 Mai 2023
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

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by