How can I compute the sum and average of odd numbers by using the loop method ?
4 次查看(过去 30 天)
显示 更早的评论
For example, if I have a vector A. A=[23 44 2 -4 -19 15 1 -70 78] then how can I compute the sum and the average of all the odd numbers by using only the loop method and no built-in functions ?
With the built-in functions I get 20 and 5 for the sum and the average of the odd numbers, but how can I compute that same answer with the loop method.
thanks,
0 个评论
采纳的回答
David Sanchez
2014-2-14
A=[23 44 2 -4 -19 15 1 -70 78];
sum = 0;
N_odds = 0;
for k=1:numel(A)
if mod(A(k),2)
sum=sum+A(k);
N_odds = N_odds + 1;
end
end
my_average = sum/N_odds;
sum =
20
my_average =
5
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!