I need help with this question

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

whats xn?
they didn't give us
it's x and subscript n
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
Is this correct?
function u=seqtan(x0)
x=x0;
y=x-tan(x);
while delta > etol
y=x-tan(x);
x=y;
x0=8;
etol=2e-10;
y=x-tan(x);
delta= abs(y-x)/abs(y)
x=y;
while delta > etol
y=x-tan(x);
delta= abs(y-x)/abs(y);
u=y;
end
end
(b)
>> u=y;
>> u
end
u =
14.7997
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.

Sign in to comment.

Answers (2)

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

How would you write it up. I'm a little confused with the writing u gave

Sign in to comment.

Tawanda Le Bourne
Tawanda Le Bourne on 12 Nov 2018
I tried this but I'm not getting the answer wen I put in the values

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 12 Nov 2018

Commented:

on 12 Nov 2018

Community Treasure Hunt

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

Start Hunting!