user3088822
user3088822

Reputation: 13

MATLAB Equation as User Input to work with

I'm trying to write a simple script that request a equation as input and I like to calculate with this function more than once without always requesting user input.

My current script defined f as function handle and executed the function 2 times, so I'm always asking for a new equation, which is not desirable.

f = @(x) input('f(x) = ');
a = f(2);   % requests user input
b = f(3);   % requests user input again

And it should look more like this (not working).

func = input('f(x) = ');
f = @(x) func;
a = f(2);
b = f(3);

And here without user input to get an idea what I try to achieve.

f = @(x) x^2;
a = f(2);
b = f(3);

I think I found a solution with Symbolic Math Toolbox, but I do not have this addon, so I cannot use/test it.

Is there another solution?

Upvotes: 1

Views: 588

Answers (1)

rayryeng
rayryeng

Reputation: 104555

There's no need for the Symbolic Mathematics Toolbox here. You can still use input. Bear in mind that the default method of input is to directly take the input and assign it as a variable where the input is assumed to be syntactically correct according to MATLAB rules. That's not what you want. You'll want to take the input as a string by using the 's' option as the second parameter then use str2func to convert the string into an anonymous function:

func = input('f(x) = ', 's');
f = str2func(['@(x) ' func]);
a = f(2);
b = f(3);

Take note that I had to concatenate the @(x) anonymous function string with the inputted function you provided with input.

Example Run

Let's say I want to create a function that squares every element in the input:

>> func = input('f(x) = ', 's');
f(x) = x.^2
>> f = str2func(['@(x) ' func])

f = 

    @(x)x.^2

>> a = f(2)

a =

     4

>> b = f(3)

b =

     9

Take special note that I assumed the function will element-wise square each elements in the input. The . operator in front of the exponentiation operator (i.e. ^) is very important.

Upvotes: 4

Related Questions