Clear Filters
Clear Filters

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 view (last 30 days)
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?

Answers (2)

Aquatris
Aquatris on 23 Aug 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 on 23 Aug 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))

Categories

Find more on Just for fun in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!