MATLAB: I am trying to find the absolute relative error of an iteration and i cant get it to work.here is the code.the equation seems to give me wrong results and then i cant get the switch statement to work.what am i doing wrong

homework

while e > tol && i==x_max;
e=((x(i+1)-x(i))/x(i+1))*100;
end
switch (e)
case {e< tol}
fprintf('Success!The result is %.4f\n',e)
case {i==x_max}
fprintf('Maximum number of iteration used.')
case {-e}
fprintf('The number was negative.')
end

Best Answer

aristi - I don't understand the condition in your while loop
e > tol && i==x_max
You want to continue to do something (calculate e) so long as e is greater than some tolerance tol and only if i is identical to x_max. Why the last part of the condition especially as i never changes within the body of your while loop? I would think that you would want to do this so long as i is less than x_max as
k = 1;
while e > tol && k < x_max
e = ((x(k+1)-x(k))/x(k+1))*100;
k = k + 1;
end
(As an aside, using i and j as indexing variables should be discouraged since MATLAB uses these as representations of the imaginary number.)
The above assumes that x has x_max elements so that is why k must always be less than x_max (since we consider x(k+1) when calculating e).