Filter löschen
Filter löschen

For/if loop for adding up only odd numbers

25 Ansichten (letzte 30 Tage)
Dobs
Dobs am 9 Nov. 2021
Bearbeitet: Yongjian Feng am 9 Nov. 2021
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

Antworten (1)

Yongjian Feng
Yongjian Feng am 9 Nov. 2021
Bearbeitet: Yongjian Feng am 9 Nov. 2021
You mean this?
for n = 1:100
if mod(n,2) == 1
c = (1/(n^2));
sum(c);
end
end
Refer to this for how to compute remainder in matlab.
  2 Kommentare
Dobs
Dobs am 9 Nov. 2021
Yes, thank you! So is mod similar to rem?
Yongjian Feng
Yongjian Feng am 9 Nov. 2021
Bearbeitet: Yongjian Feng am 9 Nov. 2021
Little bit different for negative value. Same for positive:

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by