What mistake I am making?

1 visualización (últimos 30 días)
Manav Divekar
Manav Divekar el 10 de Nov. de 2021
Comentada: Manav Divekar el 11 de Nov. de 2021
I have write a for loop to get the average of positive multiples of 7 from [ 2 14 28 -7 5 ], with using sum function.
function [avg] = avgpositive7multiples_for (m)
i = 1;
s = 0;
a = 0;
if m(m >= 0)
for t = 1:length(m)
i = t(find(mod(t,7)==0));
s = s + i;
a = numel(i);
end
end
avg = s/a;

Respuesta aceptada

Voss
Voss el 10 de Nov. de 2021
Using a loop:
function [avg] = avgpositive7multiples_for (m)
s = 0;
a = 0;
for t = 1:length(m)
if m(t) > 0 && mod(m(t),7) == 0
s = s + m(t);
a = a + 1;
end
end
avg = s/a;
Using logical indexing:
avg = mean(m(m>0 & mod(m,7) == 0));

Más respuestas (1)

DGM
DGM el 10 de Nov. de 2021
Try this
m = [ 2 14 28 -7 5 ];
avgpositive7multiples_for(m)
ans = 21
function [avg] = avgpositive7multiples_for(m)
m = m(m >= 0); % remove nonpositive values
m = m(find(mod(m,7)==0)); % extract only multiples of 7
% calculate sum
s = 0;
for k = 1:length(m)
s = s + m(k);
end
avg = s/numel(m);
end

Categorías

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

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by