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