What mistake I am making?

1 visualizzazione (ultimi 30 giorni)
Manav Divekar
Manav Divekar il 10 Nov 2021
Commentato: Manav Divekar il 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;

Risposta accettata

Voss
Voss il 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));

Più risposte (1)

DGM
DGM il 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

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by