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 vues (au cours des 30 derniers jours)
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?

Réponses (2)

Aquatris
Aquatris le 23 Août 2018
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 le 23 Août 2018
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))

Catégories

En savoir plus sur Just for fun dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by