function - MATLAB Equation as User Input to work with -
i'm trying write simple script request equation input , calculate function more once without requesting user input.
my current script defined f function handle , executed function 2 times, i'm asking new equation, not desirable.
f = @(x) input('f(x) = '); = f(2); % requests user input b = f(3); % requests user input again and should more (not working).
func = input('f(x) = '); f = @(x) func; = f(2); b = f(3); and here without user input idea try achieve.
f = @(x) x^2; = f(2); b = f(3); i think found solution symbolic math toolbox, not have addon, cannot use/test it.
is there solution?
there's no need symbolic mathematics toolbox here. can still use input. bear in mind default method of input directly take input , assign variable input assumed syntactically correct according matlab rules. that's not want. you'll want take input string using 's' option second parameter use str2func convert string anonymous function:
func = input('f(x) = ', 's'); f = str2func(['@(x) ' func]); = f(2); b = f(3); take note had concatenate @(x) anonymous function string inputted function provided input.
example run
let's want create function squares every element in input:
>> func = input('f(x) = ', 's'); f(x) = x.^2 >> f = str2func(['@(x) ' func]) f = @(x)x.^2 >> = f(2) = 4 >> b = f(3) b = 9 take special note assumed function element-wise square each elements in input. . operator in front of exponentiation operator (i.e. ^) important.
Comments
Post a Comment