What mistake I am making?

2 次查看(过去 30 天)
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

类别

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