2

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?

Shrey Gupta
  • 5,509
  • 8
  • 45
  • 71

4 Answers4

10

You can use anonymous functions:

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

and then write

>> f(2)

ans =

     4
Jan
  • 4,932
  • 1
  • 26
  • 30
4

Without the Symbolic Math Toolbox, you can still do something similar. One way to do it would be to define x as a vector of discrete values and calculate f over that:

x = 0:0.01:10; %// lower bound, step size, upper bound
f = x.^2;      %// use the element-wise power operator .^
y = f(x == 2); %// get the value for f where x is 2
Eitan T
  • 32,660
  • 14
  • 72
  • 109
Junuxx
  • 14,011
  • 5
  • 41
  • 71
2

Of course you can simply define it in an .m file: Eg In f.m: function [x] = f(x);x = x ^ 2;

>> f(2)

ans =

     4
Josh Greifer
  • 3,151
  • 24
  • 25
0

You can do this

syms x

f = x^2

subs(f,2)

ans

4