简体   繁体   English

使用一个函数的输出作为另一个函数的输入

[英]Using outputs from one function as inputs in another

Currently trying to write a function which is using the outputs of a previous function. 目前正在尝试编写一个使用前一个函数输出的函数。 The outputs are as follows: 产出如下:

f(x) = exp(x) -3*x.^2
fp(x) = exp(x) -6*x
fpp(x) = exp(x) -6

The new function is: 新功能是:

x_new = x - 2*(f(x))*(fp(x)) / 2*(fp(x).^2) -(f(x))*(fpp(x))

Tried to write [f,fp,fpp] = fun(x) because it worked for me in a script file earlier but now its saying 试着写[f,fp,fpp] = fun(x)因为它早先在一个脚本文件中对我起作用但是现在它的说法

error not enough input arguments 错误输入参数不够

Any ideas greatly appreciated. 任何想法都非常感激。

The original question: 原来的问题:

这个问题

I don't know why it is not working but I think code below works well for me: 我不知道为什么它不起作用,但我认为下面的代码对我来说效果很好:

function[f,fp,fpp,x_new]=fun(x) 
f=exp(x) -3*x.^2 ;
fp=exp(x) -6*x ;
fpp=exp(x) -6;
x_new= x - 2*(f)*(fp) / 2*(fp.^2) -(f)*(fpp);
return


x=1234;
for ind=1:10
  [f,fp,fpp,x]=fun(x);
end

I'm not sure about the math here, but you need only one function, that should look something like this: 我不确定这里的数学,但你只需要一个函数,它应该是这样的:

function r = halley(fun,x0,acc)
syms x
fp = diff(fun);
fpp = diff(fp);
x_new = symfun(x - 2*(fun(x))*(fp(x)) / 2*(fp(x).^2) -(fun(x))*(fpp(x)),x);
xold = x0;
xnew = x_new(xold);
while abs(fun(xold)) < acc && abs(xold-xnew) > acc
    tmp = xnew;
    xnew = x_new(xold);
    xold = tmp;
end
r = xnew;
end

and then you call it from a script with another function as input: 然后从另一个函数作为输入的脚本中调用它:

acc = 1.0e-8;
x0 = -5;
syms x
fun = symfun(exp(x) -3*x.^2 +1,x);
r = halley(fun,x0,acc)

however, in this exercise it says that the input of the function should be a function handle, like @fun , so maybe you should not use symbolic math? 但是,在本练习中,它说函数的输入应该是函数句柄,比如@fun ,所以也许你不应该使用符号数学? I hope this makes things clearer, though I don't know how this method should work. 我希望这会让事情变得更清楚,尽管我不知道这种方法应该如何运作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM