How do you use the integral function when the function being integrated is a user defined input?

5 views (last 30 days)
I am currently having trouble figuring out how to integrate a function when that function is being inputted by the user. This is what I currently have...
lowb=input('low: '); highb=input('high: ');
fun=@(x)([input('input function here: ')]); B=integral(fun,lowb,highb);
I have the user input the upper and lower bounds, as well as the function they want integrated. However, turning the inputted function into something the integral function can work with is where I am lost. Any help would be awesome, thanks.

Answers (1)

Jyotish Robin
Jyotish Robin on 31 Mar 2017
Edited: Jyotish Robin on 31 Mar 2017
Hi Brennan!
I hope "str2func" function in MATLAB will do the trick.
fh = str2func(c)
constructs a function handle, fh, from a function name or a character vector that defines an anonymous function.
You can convert a character vector that represents an anonymous function to a function handle.
Example : Define a character vector that represents the anonymous function 7x – 13. Convert the character vector to a function handle.
str = '@(x)7*x-13';
fh = str2func(str)
This gives:
fh =
@(x)7*x-13
If you want to read more about this function, have a look at https://www.mathworks.com/help/matlab/ref/str2func.html
You may find the below link also interesting:
Hope the above suggestions help.
Regards,
Jyotish

Categories

Find more on MATLAB 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!