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 ビュー (過去 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 Center および File ExchangeDiscrete Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by