I need help with this question
Show older comments
Consider the sequence defined by xn+1 = xn − tan(xn) for some initial value x0.
(a) Write a MATLAB function seqtan that takes the values x0 and etol as inputs, and calculates the terms of the sequence above until the stopping criterion xn+1 − xn/|xn+1|< etol is satisfied. The function should output the final calculated term of the sequence and store the value as x.
(b) Write a MATLAB command that executes seqtan with x0 = 8 and etol = 2 × 10^−10 and stores the resulting output as u.
THIS IS WHAT I DID
function x= seqtan(x0,etol
x=1;
y=x-tan(x);
x=y;
while delta > etol
y=x-tan(x);
delta=abs(y-x)
x=y;
end
6 Comments
madhan ravi
on 12 Nov 2018
whats xn?
Tawanda Le Bourne
on 12 Nov 2018
Tawanda Le Bourne
on 12 Nov 2018
Walter Roberson
on 12 Nov 2018
How is this not a duplicate of https://www.mathworks.com/matlabcentral/answers/429321-hi-i-need-help-solving-a-question-i-m-not-sure-how-to-go-about-solving-it-i-m-very-new-to-matlab-c
Tawanda Le Bourne
on 12 Nov 2018
Edited: Walter Roberson
on 12 Nov 2018
Walter Roberson
on 12 Nov 2018
There is no need to set x0 multiple times.
You should not be setting x0 to 8 or setting arbitrarily. You should be using the x0 and etol value the user pased in. The function needs to take two parameters, x0 and etol.
Typically if you have nested while loops you should be asking yourself whether the code is correct. Nested while loops are necessary sometimes, but they tend to hint that the programmer might not understand while loops.
Answers (2)
Guillaume
on 12 Nov 2018
Well, have you tried to run your code? There's a syntax error on the first line that you can correct yourself easily. Once you've done that you would get an undefined function or variable delta error since you use delta on the first iteration of your loop without having calculated it.
Other than that I see nothing wrong with your code, other than the minor issue of a missing semicolon on the delta= line.
Note that a way to avoid to calculate anything before the loop and thus avoid duplicated efforts (and double the possibility of mistakes) is to convert a loop of the form:
%calculate first iteration
while condition
%calculate 2nd and all subsequent iterations
end
to
while true
%calculate 1st, 2nd and all subsequent iterations
if ~condition
break;
end
end
1 Comment
Tawanda Le Bourne
on 12 Nov 2018
Tawanda Le Bourne
on 12 Nov 2018
0 votes
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!