MATLAB help with function and while loop?

3 Ansichten (letzte 30 Tage)
Lauren Hux
Lauren Hux am 13 Nov. 2016
Bearbeitet: Roger Stafford am 14 Nov. 2016
Whenever I try to call this function, I get the error: Subscript indices must either be real positive integers or logicals. Any help?
  1 Kommentar
Daniel kiracofe
Daniel kiracofe am 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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Roger Stafford
Roger Stafford am 13 Nov. 2016
Bearbeitet: Roger Stafford am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by