Borrar filtros
Borrar filtros

how to calculate the mean using loop

2 visualizaciones (últimos 30 días)
Jincy
Jincy el 25 de Mayo de 2023
Comentada: Jincy el 28 de Mayo de 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 comentarios
Walter Roberson
Walter Roberson el 25 de Mayo de 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 el 28 de Mayo de 2023
Thank you

Iniciar sesión para comentar.

Respuestas (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 25 de Mayo de 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

Categorías

Más información sobre GPU Computing en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by