I want to make a programming function in which I want to take input any mathematical function like f(x)=sin(x)+x^2. then I take a input x and my function return a value of f(x).but i don't know how can i do?

1 次查看(过去 30 天)
I want to make a programming function in which I want to take input any mathematical function like f(x)=sin(x)+x^2. then I take a input x and my function return a value of f(x).but i don't know how can i do?

回答(2 个)

Aquatris
Aquatris 2018-8-23
Here is a simple Matlab script;
f_math = @(x) sin(x)+x.^2;% mathematical function, notice the element wise operation
fun = @(f,x) f(x); % function that takes mathematical function and x
x = 1:1:100; % input x
y = fun(f_math,x); % output f(x)

James Tursa
James Tursa 2018-8-23
E.g.,
s = input('Input a function of x: ','s');
f = str2func(['@(x)' vectorize(s)]);
Now you have a vectorized function handle version of the function character string that was input from the user. A sample run:
>> s = input('Input a function of x: ','s')
Input a function of x: sin(x) + x^2
s =
sin(x) + x^2
>> f = str2func(['@(x)' vectorize(s)])
f =
@(x)sin(x)+x.^2
>> x = linspace(0,2*pi,100);
>> plot(x,f(x))

类别

Help CenterFile Exchange 中查找有关 Just for fun 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by