MATLAB help with function and while loop?
3 views (last 30 days)
Show older comments
Whenever I try to call this function, I get the error: Subscript indices must either be real positive integers or logicals. Any help?

1 Comment
Daniel kiracofe
on 13 Nov 2016
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
Answers (1)
Roger Stafford
on 13 Nov 2016
Edited: Roger Stafford
on 14 Nov 2016
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 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!