While loop isn't working

조회 수: 46 (최근 30일)
StillANovice
StillANovice 2020년 8월 23일
편집: TADA 2020년 8월 23일
Hello,
My function is as follows:
function root = NM(f, f1, x_0, epsilon, iteration)
x = zeros(1, 50);
x(1) = x_0;
count = 0;
while abs(f(x)) < epsilon
count = count + 1;
if count > iteration
break
end
x = x - f(x)/f1(x);
end
root = x;
end
Here's how I tried to test my function:
clear
syms t
x_0 = 2*pi/3;
epsilon = 0.0001;
iteration = 30;
v = @(t) sin(t);
vprime = matlabFunction(diff(v(t)));
root1 = NM(v, vprime, x_0, epsilon, iteration)
The loop does not seem to work, as the result I got was the initial value 2pi/3. What have I done wrong?
  댓글 수: 4
TADA
TADA 2020년 8월 23일
편집: TADA 2020년 8월 23일
still not running, I assume you should change it from f to v?
Adam Danz
Adam Danz 2020년 8월 23일
You could probably see what's wrong by investigating the variables in debug mode and it will probably be much faster than the time it will take to explain things to use and wait for a response.
Follow the instructions in this comment to use debug mode.

댓글을 달려면 로그인하십시오.

채택된 답변

TADA
TADA 2020년 8월 23일
You have two mistakes
1. while loop should work with a scalar condition, but as far as I know if you use a logical vector it will only enter the loop if all values are true:
% endless loop - as expected
while true
disp(rand(1));
end
% never enters loop - as expected
while false
disp(rand(1));
end
% endless loop
while [true true]
disp(rand(1));
end
% never enters loop
while [false true]
disp(rand(1));
end
% never enters loop
while [true false]
disp(rand(1));
end
So when you declared x as a vector 1x50 you booby trapped your loop. just initialize x to the x_0 value
x = x_0;
2. In your loop condition you checked if the value is smaller than the tolerance value instead of larger, so naturally it will never enter the loop unless by luck you started from zero:
while abs(f(x)) > epsilon T % should work
  댓글 수: 2
StillANovice
StillANovice 2020년 8월 23일
Hey, thanks! - silly mistakes...
If I were to be more pedantic, what is the correct way to implement preallocation?
TADA
TADA 2020년 8월 23일
편집: TADA 2020년 8월 23일
your preallocation was fine, it could be improved by using the input of number of iterations as vector size (that is if the vector size correlated to number of iterations):
x = zeros(1, iteration);
The problem wasn't the preallocation though, the problem was how you used it later on

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by