Matlab while loop complicated function. Help me figure this out.

I need to modify the statement in the while loop so that it allows me to check the termination of the loop when the conditional is greater than delta and it is less than maxit. Run your function to compute the square root of a prime number between 50 and 100 using a delta value of 5E‐3 and maxit of 10.
function Novikov(x,delta,maxit)
%The simple square root function with added functionality
%%Synopsis: Call the function NewtonSqrt and pass a numerical value 'a'
%whose square root we need to approximate. Pass also delta and maxit for
%convergence control
it = 0;
if nargin<2,delta=5E-6;end
if nargin<3, maxit=5; end
r=x/2;
rold=x;
%Use fprintf command as a place holder
fprintf('\n the estimate for the square root of x is \n')
%disp(['The approach to sqrt(a) for a=',num2str(a)]);
%i=0;
while abs((r-rold)/rold)>delta
%while i<6
it = it + 1;
it < maxit;
rold=r; %Save old value of r for next convergence
r=0.5*(rold+x/rold);
disp(r)
%i=i+1;
end
fprintf('%14.6f \n', r)
%disp('Matlab''s value: ')
fprintf('Matlab''s value is: ')
disp(sqrt(x))

 采纳的回答

Write a combined logic test of the two conditions in the initial while statement. Since this is homework, a hint rather than actual code...there's an example as the last example under
doc while
that's described as taking advantage of short-circuiting(*) but it shows how one writes the compound expression syntactically.
() Of course, the link under 'Tips' directly under it comments that "within an if or while expression, all logical operators, including | and &, short-circuit" so the explicit use of *&& in the example is all for naught. But, that's not the point of the example for you, simply how to write the compound test expression you're looking for.

更多回答(0 个)

类别

在 帮助中心 和 File 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