How can I turn an equation into a string for input?

A function I am trying to use requires the function input to be a string. For example taking the equation "f(x)=x^2 - x + 5" as an input, but needing to be a string.
I am unsure of how to turn this into a string that the function will then accept (uses feval). All the questions I've found from researching use "str2sym" but I don't believe this is doing what I need.
Thanks in advance for your help.

2 Comments

How exactly is the function defined in your code? "f(x)=x^2 - x + 5" already looks like a string to me.
Well that's half my issue I think. I am not sure how to define it properly, it's a very basic thing I cannot seem to find the answer for.
What I have tried to write is the equivalent of:
f='x^2-x+5';
Then I would call the function:
function(f,a,b,c)
and I will get an error due to how I have defined f (where a,b,c are just parameters to add for the operation). The function comments has "f is the function input as a string 'f' "

Sign in to comment.

Answers (1)

str2func should work:
s = input('Enter the function:\n');
% Enter the function:
% '@(a,x) a*sin(x) - 1/2'
f = str2func(s);
Dont forget quotes

Categories

Products

Release

R2018b

Asked:

on 29 Aug 2019

Commented:

on 29 Aug 2019

Community Treasure Hunt

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

Start Hunting!