MATLAB help with function and while loop?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Whenever I try to call this function, I get the error: Subscript indices must either be real positive integers or logicals. Any help?

1 commentaire
Daniel kiracofe
le 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
Réponses (1)
Roger Stafford
le 13 Nov 2016
Modifié(e) : Roger Stafford
le 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 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!