MATLAB help with function and while loop?
조회 수: 3 (최근 30일)
이전 댓글 표시
Whenever I try to call this function, I get the error: Subscript indices must either be real positive integers or logicals. Any help?

댓글 수: 1
Daniel kiracofe
2016년 11월 13일
Your code looks okay to me. I don't see anything wrong off the top of my head. Suggest that you take a look at points #3 and 5 in the below and add more detail.
https://www.mathworks.com/matlabcentral/answers/6200-tutorial-how-to-ask-a-question-on-answers-and-get-a-fast-answer
답변 (1개)
Roger Stafford
2016년 11월 13일
편집: Roger Stafford
2016년 11월 14일
I see at least four difficulties in your code:
a) You shouldn’t use the word ‘sum’ for a variable. Matlab has a function by that name and this function expects an argument. Use some other name.
b) The series you describe does not converge to e. Probably it is 1/k! = 1/factorial(k) that you are thinking of.
c) The variable ‘answer’ remains at a constant value of 1, not e, so your while loop would never stop, (once you correct the above a) error.)
d) In the line:
term = sum+1/k^2;
the variable 'term' would not be the next term but would be the partial sum and therefore the next line would be totally incorrect:
sum = sum+term;
It would amount to calculating the cumulative sum of partial sums - something you certainly don't want. Correction: No, it would actually amount to a kind of doubling of partial sums at each step. It would very soon overflow matlab's maximum possible numerical value, 'realmax', which is a terrifically large number.
Addendum: The sum of the infinite series 1/k^2 would actually give you pi^2/6. To show this, look up the definition of the first Bernoulli number, B1, and its value.
댓글 수: 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!