I'm not sure how to relate a counter

์กฐํšŒ ์ˆ˜: 1 (์ตœ๊ทผ 30์ผ)
Saskiaa Vamadevan
Saskiaa Vamadevan 2022๋…„ 4์›” 7์ผ
๋Œ“๊ธ€: Riccardo Scorretti 2022๋…„ 4์›” 7์ผ
I have a equation:
โˆž
๐‘’ = โˆ‘ ๐‘›!
n = 0
I need to some how relate the counter, which starts at 1, with the factorial n that starts at 0. But I'm not sure how to go about this.
I need to make j=1 when n=0 and so on j=1,2,3,4,5,6... when n=0,1,2,3,4.....
i have to do this via for loops to get the first 10 terms of the sequence as well as calulating the series then plotting it.
I'm not sure how to relate the counters, how to make j=1 when n=0 and so on.

๋‹ต๋ณ€ (1๊ฐœ)

Riccardo Scorretti
Riccardo Scorretti 2022๋…„ 4์›” 7์ผ
ํŽธ์ง‘: Riccardo Scorretti 2022๋…„ 4์›” 7์ผ
Hi Saskiaa, if the question is just "how to have j = 1, 2, 3 ... when n = 0, 1, 2 ..." it is enough to write the loop with respect of one of the two variables (namely n) and then compute the other, for instance:
for n = 0 : 9
j = n + 1;
% some other computation
end
However, I guess that in your particualr example the problem is that 0! = 1! = 1. You could handle separately the case n=0 by rewriting the sum like:
This gives something like:
value = 1.0;
fact = 1.0;
for n = 1 : 10
fact = fact * n;
value = value + 1/fact;
end
fprintf('sum = %20.15f (reference = %20.15f)\n', value, exp(1));
sum = 2.718281801146385 (reference = 2.718281828459045)
Notice that this kind of code is for pedagogical purpose only. In "true" Matlab coding, I would rather vectorize like that:
fact = cumprod(1:10);
value = 1.0 + sum(1./fact);
fprintf('sum = %20.15f (reference = %20.15f)\n', value, exp(1));
sum = 2.718281801146385 (reference = 2.718281828459045)
  ๋Œ“๊ธ€ ์ˆ˜: 4
Saskiaa Vamadevan
Saskiaa Vamadevan 2022๋…„ 4์›” 7์ผ
Okay, sorry about the code formatting.
We have to do n+1 to account for the 1/0! when doing the sumtoplot. Okay, I understand now. I think I was sturggling on the starting the loop part due to n=0.
Thank you for your help
Riccardo Scorretti
Riccardo Scorretti 2022๋…„ 4์›” 7์ผ
You are welcome.

๋Œ“๊ธ€์„ ๋‹ฌ๋ ค๋ฉด ๋กœ๊ทธ์ธํ•˜์‹ญ์‹œ์˜ค.

์นดํ…Œ๊ณ ๋ฆฌ

Help Center ๋ฐ File Exchange์—์„œ Function Creation์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์•Œ์•„๋ณด๊ธฐ

์ œํ’ˆ


๋ฆด๋ฆฌ์Šค

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by