Friday, September 18, 2009

Symbolic math with Matlab

A lot of people in academia use Matlab on a regular basis. But it turns out that Matlab has so many cool features that most often, nobody knows about. This post is about one such feature, symbolic math in matlab. Matlab allows you to solve equations, do integration, differentiation and so on. All you need to do is install the Symbolic Math toolkit (which is also available on the student edition).

Here is a hello world sorta example:

>> syms x y
>> x+x
ans =
2*x

The first line says that we are using 2 symbols x and y.
The second line is any arbitrary algebra you want to do on these variables.


The symbolic math toolkit also allows you to do math using fractions:

>> sym(1/5) + sym(1/3)
ans =
9/20


Here is another simple algebra example:

>> quadeqn='a*x*x+b*x+c=0';
>> solve(quadeqn,'x')
ans =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)

This solves the quadratic equation for variable 'x'.


To actually evaluate this at some value, we can simply specify more equations. The solve function can solve a system of equations, and generate a set of results, one for each variable in the system.

>> [a,b,c,x]=solve(quadeqn,'a=1','b=1','c=1')

x =
(3^(1/2)*i)/2 - 1/2
- (3^(1/2)*i)/2 - 1/2

(it gives the values of a, b, c also, which i have removed here for brevity)

Now, typing:

>> simplify((3^(1/2)*i)/2 - 1/2)

-0.5000 + 0.8660i

This is the more easy to read answer we wanted :)

Speaking of simplify, there are some really whacky functions in matlab for symbolic simplification:

>> simplify(cos(x)^2 + sin(x)^2)
ans =
1

>> simplify(a*a + 2*a*b + b*b)
ans =
(a + b)^2

Lets try something harder...

>> simplify(cos(x) + i*sin(x))
ans =
cos(x) + i*sin(x)

Oops! did it give up already? not to worry. Matlab has a bunch of simplification routines, and simplify is only one of them. We can invoke ALL (mwuahahaahahaa!!) of them by using the 'simple' function.

>> simple(cos(x) + i*sin(x))
(matlab goes on a big spin, spews out lots of stuff, but finally...)
ans =
exp(i*x)

Sometimes you want to go the other way:

>> expand ((a+b)^2)
ans =
a^2 + 2*a*b + b^2


And then, we have differentiation:

>> diff(sin(x)^3)
ans =
3*cos(x)*sin(x)^2


...partial differentiation with respect to x:

>> diff(x^2 + y^2 + c, 'x')
ans =
2*x


...And integration:

>> int(sin(x)^3)
ans =
cos(3*x)/12 - (3*cos(x))/4


And all this with discontinuous functions and limits :D :D :D

>> int(dirac(x-a)*x^2,-inf,inf)
ans =
a^2


Then there is function composition:

>> f=log(x);
>> g=sin(x);
>> compose(f,g)
ans =
log(sin(x))


And a whole host of other cool things waiting for you... hope this kick starts a new interest in the awesome powers of matlab.

Note: Matlab by no means has the best symbolic math toolkit, but its more commonly found than Mathematica :P