[英]This if is not working on Octave/Matlab
I have the code divided on three functions: 我将代码分为三个功能:
fm
(This function works ) fm
(此功能有效 )
function y=f(x)
y = x^2;
endfunction
df.m
(The function that return the derivate of y=x^2
. This function works ) df.m
(返回y=x^2
的导数的函数。此函数有效 )
function y=df(i)
syms x,diff(f(x),x);
subs(ans,x,i);
y = ans;
endfunction
newton.m
( maxIt
= max of tries) newton.m
( maxIt
=最大尝试次数)
function [x1,nIt] = newton (f,df,x0,tol,maxIt)
k=0;
x=x0;
nIt = 0;
while (k<maxIt)
if(df(x)== 0)
fprintf("La derivada, da resultado 0");
k=maxIt;
else
i = x - (f(x)/df(x))
x = i;
nIt = nIt + 1
k=k+1;
endif
end
endfunction
Ok, I executed the command newton(@f,@df,0,10,2)
. 好的,我执行了命令
newton(@f,@df,0,10,2)
。 Two-thirds of the program works OK, but if I do df(0)
, the result is 0
but the if
doesn't work. 程序的三分之二工作正常,但是如果我执行
df(0)
,结果为0
但if
不起作用。 I verified that df(0)
returns 0, and it's OK. 我验证了
df(0)
返回0,并且可以。
I´m new in MATLAB/Octave. 我是MATLAB / Octave的新手。
You have several mistakes in your code. 您的代码中有几个错误。 Not all of them are directly relevant, but fixing all of them will make your code more readable and robust.
并非所有这些都直接相关,但是修复所有这些将使您的代码更具可读性和鲁棒性。
The function f
if fine. 函数
f
如果可以)。
The function df
assumes that f
is known somehow, but it's not a good practice. 函数
df
假定f
是以某种方式已知的,但这不是一个好习惯。 you better pass f
too to this function. 您最好也将
f
传递给此函数。 Also, don't use ans
as a variable, store your intermediate result in different variables. 另外,请勿将
ans
用作变量,而是将中间结果存储在不同的变量中。 This is how df should look: 这是df的外观:
function y = df(f,a)
syms x
d = diff(f(x),x);
y = subs(d,x,a);
end
Now you have to change all the calls to df
in your newton
function to df(f,x)
. 现在,您必须将
newton
函数中所有对df
的调用更改为df(f,x)
。 I'm not sure what is your final goal, but right now, the variables x1
and tol
are not in use in any way. 我不确定您的最终目标是什么,但是现在,变量
x1
和tol
并未以任何方式使用。
Hope it solves the problem ;) 希望它能解决问题;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.