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 visualizzazioni (ultimi 30 giorni)
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?

Risposte (2)

Aquatris
Aquatris il 23 Ago 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 il 23 Ago 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))

Categorie

Scopri di più su Just for fun in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by