How can i modify this code so x can = 0

function qw=fNR(x)
qw=zeros(100,1)
qw(2)=x
i=2
while abs(qw(i)-qw(i-1))>1e-6
qw(i+1)=qw(i)-ff1(qw(i))/fdf1(qw(i))
i=i+1
end
qw=qw(2:i-1)
[qw(end) i]
plot(qw)
end
how can i model this functio so it can take fNR(0)
fdf1
function y=fdf1(x)
y=3*x.^2-12*x+11;
end
ff1
function y=ff1(x)
y=x.^3-6*x.^2+11*x-5;
end

답변 (1개)

Image Analyst
Image Analyst 2022년 2월 12일

0 개 추천

Try this:
function qw=fNR(x)
qw=zeros(100,1)
qw(2)=x
i=2
maxIterations = 1000;
loopCounter = 0;
while (abs(qw(i)-qw(i-1))>1e-6) && loopCounter < maxIterations
qw(i+1)=qw(i)-ff1(qw(i))/fdf1(qw(i))
i=i+1
loopCounter = loopCounter + 1;
end
qw=qw(2:i-1)
if isempty(qw)
message = sprintf('qw is empty')
uiwait(warndlg(message));
return;
end
[qw(end) i]
plot(qw)
end

댓글 수: 5

Muhammad Choudhury
Muhammad Choudhury 2022년 2월 12일
편집: Muhammad Choudhury 2022년 2월 12일
when i call fNR(0) i get an error message:
Array indices must be positive integers or logical values.
Error in fNR (line 12)
[qw(end) i] %this displays on the screen the last value of the iteration
That's showing up because the loop never starts. Since the loop never starts, pruning the vector:
qw=qw(2:i-1);
results in a zero-length vector. Trying to index to qw(end) is the same as qw(0), which isn't a valid index.
You can at least get it to start by doing this.
i=2;
dqw = 1;
while dqw > 1e-6
qw(i+1) = qw(i)-ff1(qw(i))/fdf1(qw(i));
[qw(i) qw(i-1)]
dqw = abs(qw(i)-qw(i-1))
i = i+1;
end
ah thanks makes sense
DGM
DGM 2022년 2월 12일
Oops. I didn't realize I was commenting on the answer instead of on the question.
Image Analyst
Image Analyst 2022년 2월 13일
@Muhammad Choudhury I know that was your error with the original code. Obviously you never ran my code because my code throws up an alert that the array is empty rather than your error.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2022년 2월 12일

댓글:

2022년 2월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by