Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Can anyone help me with this code? I want to find the x(n) that has an Error smaller than Criteria. The code seems never stop and I don't know what's wrong with my code. Thanks

1 vue (au cours des 30 derniers jours)
Qiuyi Wei
Qiuyi Wei le 1 Avr 2019
Clôturé : MATLAB Answer Bot le 20 Août 2021
Criteria = 2*rand;
y = @(x) 0.1.*x.^4-2.*x.^3+8.*x.^2+10.*cos(x);
dydx = @(x) 0.4.*x.^3-6.*x.^2+16.*x-10.*sin(x);
x1 = 5;
x2 = x1-y(x1)./dydx(x1);
Error = 100.*abs(x2-x1)./x2;
x(1) = 5;
for n = 2:4
while Error >= Criteria
x(n) = x(n-1)-y(x(n-1))./dydx(x(n-1));
Error(n) = 100.*abs(x(n) - x(n-1))./x(n);
end
BestGuess = x(n);
end

Réponses (1)

Walter Roberson
Walter Roberson le 1 Avr 2019
You assign to Error(n), so we can see that Error is expected to be a vector. But your while loop is
while Error >= Criteria
We just established that Error is expected to be a vector, so this is a vector test of all elements in Error to Criteria. When you use a vector of values in if or while the test is considered true only if all the tests are true. If there is any element in Error which is < Criteria then the loop would stop. This is important because after you manage to get through the while loop once, on the next value of for, that Error(n-1) is still there in the vector and is known to be < Criteria or else the previous iteration would not have ended...

Community Treasure Hunt

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

Start Hunting!

Translated by