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
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
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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by