For/if loop for adding up only odd numbers
조회 수: 29 (최근 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!