What mistake I am making?

조회 수: 2 (최근 30일)
Manav Divekar
Manav Divekar 2021년 11월 10일
댓글: Manav Divekar 2021년 11월 11일
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;

채택된 답변

Voss
Voss 2021년 11월 10일
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));

추가 답변 (1개)

DGM
DGM 2021년 11월 10일
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
Manav Divekar
Manav Divekar 2021년 11월 11일
Thank you that helped

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by