Question

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?

Was it helpful?

Solution

You can use anonymous functions:

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

and then write

>> f(2)

ans =

     4

OTHER TIPS

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

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

You can do this

syms x

f = x^2

subs(f,2)

ans

4

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top