For/if loop for adding up only odd numbers
22 次查看(过去 30 天)
显示 更早的评论
Hi,
We're supposed to write a loop (it must be a loop!) to calculate the following expression (see attached image). We're supposed to only sum the values that correspond to odd values of n.
This is what I got so far but I don't know how to specifiy that only only odd values for n are added.
for n = 1:100
c(n) = (1/(n^2));
sum(c);
end
Can anybody help me with that please?
Thanks,
Debbie
0 个评论
回答(1 个)
Yongjian Feng
2021-11-9
编辑:Yongjian Feng
2021-11-9
You mean this?
for n = 1:100
if mod(n,2) == 1
c = (1/(n^2));
sum(c);
end
end
2 个评论
Yongjian Feng
2021-11-9
编辑:Yongjian Feng
2021-11-9
Little bit different for negative value. Same for positive:
另请参阅
类别
在 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!