Search code examples
functionmathmatlabevaluate

How to evaluate a function at a point in Matlab?


For example, if I have a function f(x)=x^2, how can I evaluate it at x=2? I have tried employing the symbolic toolbox and using the following code in the Command Window:

syms x;
f = sym(x^2);
subs(f,x,2);

But I just get this error on the first line: Undefined function 'syms' for input arguments of type 'char'.

I am completely new to Matlab and still working out the syntax, so I may have a syntactical error. However, I also have a Student trial edition, so I supposedly can't use the symbolic toolbox. Is there any way I can define f(x) and evaluate it at x=2?


Solution

  • You can use anonymous functions:

    >> f = @(x) x^2;
    

    and then write

    >> f(2)
    
    ans =
    
         4