What mistake I am making?

2 vues (au cours des 30 derniers jours)
Manav Divekar
Manav Divekar le 10 Nov 2021
Commenté : Manav Divekar le 11 Nov 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;

Réponse acceptée

Voss
Voss le 10 Nov 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));

Plus de réponses (1)

DGM
DGM le 10 Nov 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
  1 commentaire
Manav Divekar
Manav Divekar le 11 Nov 2021
Thank you that helped

Connectez-vous pour commenter.

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by