1

我试图调用一个允许用户输入他们选择的方程的函数,然后使用一个单独的函数在数值分析中使用梯形规则来近似它。

这是我的用户输入方程的代码:

    function f = myf(x)
    y=@(x) input('Input Equation:  ');
    f=y(x);
    end

这是应用梯形规则的代码:

    function T=trapez(f,a,b,n)
    h=(b-a)/n;
    x=[a+h:h:b-h];
    T=h/2*(feval(f,a)+feval(f,b)+2*sum(feval,f,x));
    fprintf('The approximation by trapezoida rule is: %f with step h: %f\n',T,h);
    end

我的问题是尝试使用由第一个函数确定的方程作为第二个函数的输入。

    >> f=myfun
    Input Equation: exp(x^2)

    f = 

    @(x)exp(x^2)


    f = 

    @(x)exp(x^2)

    >> trapez(f,0,1,15)
    Error using feval
    Not enough input arguments.

    Error in trapez (line 4)
    T=h/2*(feval(f,a)+feval(f,b)+2*sum(feval,f,x));
4

1 回答 1

1

Here is the function to input the function,

function f=myf
y=input('Input equation: ','s');
eval([ 'f=@(x)' y ';'])

and use f=myf from another function.

Also your trapez unction needs some modification:

function T=trapez(f,a,b,n)
    h=(b-a)/n;
    x=[a+h:h:b-h];
    T=h/2*(f(a)+f(b)+2*sum(arrayfun(f,x)));
    fprintf('The approximation by trapezoida rule is: %f with step h: %f\n',T,h);
    end

Depending on how the function is to be input, myf could be different. This should work if you give the input as, e.g.: x^2 (so just the function, not extra syntax)

y=input('Input equation: ','s')
eval([ 'f=@(x)' y])

And a sample input/output:

Input equation: x^2
y =
x^2
f = 
    @(x)x^2

and then you can do f(2) to find 2^2.

Alternatively, if you want to input the function with its argument, e.g.: @(y) y^2

y=input('Input equation: ','s')
eval(['f=' y])

and sample output:

>> y=input('Input equation: ','s')
    eval(['f=' y])
Input equation: @(t) t^2
y =
@(t) t^2
f = 
    @(t)t^2
>> f(2)
ans =
     4
于 2014-04-15T01:42:28.280 回答