Symbolic calculation using Matlab

The thing is that some times running a simulation over and over again makes no sense. One have to see the mathematical formula that is being computed to make some safe assumptions and change his approach on a subject. Without getting in detail on where someone could use something like this, Matlab gives the possibility of symbolic calculation. That is, if I want to see how the output of function call_func affects the inputs A and B (for a really long list of reasons) I can use syms.

Thus the code:

 
syms A B
result = call_func(A,B);

The above code stores in result what would be the result but with A and B kept as symbols. So if function call_func computes the A^2 + 2*A*B + B^2 (that seems familiar…) we get:

result =
A^2 + 2*A*B + B^2

Which is pretty straightforward but I could not come up with something more practical. I use the syms command lately to observe the impact of each coefficient in an FFT. Also I used in before to get the result of the multiplication between two large matrices so that I could use it as a formula instead.

Advertisements

Matlab profiler

A really useful tool for code optimization in Matlab is the profiler. Using the profiler we can find the really computational intensive parts of our model and by trying to optimize them we can reduce heavily the computation time of the simulation. We can find the profiler on the desktop –> profiler (as seen below):

matlab_profiler01

Once opened we can run any code we want through the profiler from the “Run this code:’” bar as seen below. I run a script of my own called prediction_script.

matlab_profiler02

Once the code is ran we get a detailed report of how much time each function we use is called and how many times it is called throughout the simulation.

matlab_profiler03

In the above picture we can see that the total time of the predictor script is 52.865 seconds. However only 0.031 seconds are used to run the code in the predictor script (this is the self time). so in my case the prediction script calls the predictor twice. and the predictor calls any other function.

The most computational intensive function in my case is the get_value which is called 739180 times and lasts for 18.697 seconds. It does not call any other function (both the total and the self time are the same).

By clicking on the get_value we get the detailed information on where the most computations are done. By using the profiler often we get to know which operations are time consuming in Matlab and end up writing better code.

matlab_profiler04

As we can get information on which functions call the selected function the profiler can also be used for reverse engineering in case of unknown code.

So if I get to make the get_value function faster or I manage to call it less times then the simulation will end up faster overall. Easy as pie. A really useful tool!