# 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.

# Matlab Start Up

It is often frustrating, distracting and demotivating when I start Matlab and I have to start a series of commands, most frustrating of all the current directory. In order to automate things a bit the use of `startup.m` as well as the `finish.m` comes in handy.

To use this (in Windows there are also similar ways to use in other OS but I haven’t one available right now) one should create a shortcut (e.g. the on in start menu which I prefer as the only thing to start matlab is pressing the windows button and type “`mat`”) and edit the `start in`, in the properties menu. The target should be the directory with the `startup.m` file. In the file one can find:

```
cd c:\...<desired start up path >
...<any other matlab operation>
```

Any other matlab operation can be another script or matlab code. Typically initialization of parameters that have to do with the workspace mostly, like the plot styles and font sizes. However if you use a script you can run immediately the desired code, although I don’t find any particular reason for someone to be so hasty…

`Finish.m` works the same way and can be used to store data after finishing a simulation. As far as this is concerned I find it useful sometimes to export data to excel (like mentioned in a previous post) for further manipulation as in the following code example.

```save results/testTIMES testTIMES
save results/testSNR testSNR
save results/testBITS testBITS

xlswrite('results',testBITS,1,'B1')
xlswrite('results',testSNR,1,'C1')
xlswrite('results',testTIMES,1,'D1')```

# 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):

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.

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.

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.

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!

# MatLab from the console

The following works both for Unix and Windows systems. In order to run MatLab without the graphical interface (this is handy because in this way one can get and release licenses through a script and also having the script running slightly faster) one needs to type the following (in UNIX in Windows it is similar):

```nice matlab –nosplash –nodesktop
```

and voila!

Apart from running the MatLab instance in console one can run MatLab code from bash shell this is done with the mat command. Batch commands can be passed to MatLab by using -r command line option during invocation. By default the MatLab session keeps running. A common work around is to include a MatLab quit command explicitly in the MatLab code (the .m files), typically at the end of a simulation. An alternative is to use a wrapper script that automatically quits MatLab (a nicer solution because you can have the same code running for both instances of MatLab).

Invoking user defined M-files

```mat "yourMfile_command"
```

Calling matlab commands

```mat "help pack"
```

Display of workspace data

```mat "a = randn(1,10); disp(a)"
```

Inspecting plots (use enter key to exit the matlab session)

```mat "x = sin(0:0.2:6.28); plot(sin(x));pause"
```

Example of a mat wrapper script:

```
#!/bin/bash

if test "\$1" = ""
then
echo Usage \$0 \"matlab command\"
exit
fi
```

# Dynamic variable name change using Matlab

There are plenty of times in the past that I needed to store many different data srtuctures in different file names but I didn’t know the way to change the name of a variable during the execution of the code.

So now that I really needed to do so (storing 1500 different matrices one by one takes some time so naming them automatically while calculating them makes it much more efficient!) I searched the Matlab capabilities and found exactly what I was looking for!

Thus if for example you have table A and you want to store 10 different instances of the table like A_1 – A_10 then the eval() function is just what you need:

Here is the code that would do the trick:

```
for ii = 1 : 10
% Creating the filename
filename = [‘A_’ num2str(ii)];

% Creating the new variable name
varname = [‘A_’ num2str(ii)];

% calculating the new value of A
value = function();

% This is the instruction that will assign the value to A_ii
s = [‘A_’ num2str(ii) ‘= value ‘];

% Do not use eval with no reason because it is much slower than the normal assignment.
eval(s) ;

% Saving the result
save(filename,varname)
end```

Now lets say that we have 10 `.mat` files that need to be read from (the `A_1 – A_10`) here is how to do it:

```for ii = 1 : 10
end
```

Although the following might work as well:

```for ii = 1 : 10
filename = [‘A_’ num2str(ii)]; % Creating the filename
end
```

but I’m not sure…

So have fun storing but take into account that it will affect the whole performance so use with care!

# MatLab to Excel

Sometimes I have trouble visualizing some matrix structures that I create in MatLab. And when I get to see them in the MatLab command line or the matlab workspace it does not help much. A way to deal with that and seek and understand patterns easier is to export them in excel. MatLab supports this with the instructions:

`xlsread` (to read from an excel file) and

`xlswrite` (to write to one)

`(filename, matrix(to be written max 2 dimensions), sheet, range)`

by using the following one can create matrixes that contain both data and titles:

`matrix1 = {‘Title1', Title2'; 1 423 ; 2 742; 3 192}`

And to actually write in an excel file:

`xlswrite('matrix1.xls', matrix1, 'Example Sheet', 'E1')`

It is needless to point out the usefulness of this. One can either import data to MatLab from an excel (which amy be automated to produce desired data and easily editable) and once the simulation is done and the results are calculated they can be exported for further analysis in an excel too.

Both tools are very powerful mathematical tools each one with different properties. The combination of these both can really give solutions to many problems!

# MatLab email feature

In case you want to have MatLab sending you an email to notify you about a simulation that ended or crashed you can use the following:

```% Set up preferences. I think this is only needed once
setpref('Internet','E_mail',mail);
setpref('Internet','SMTP_Server','smtp.gmail.com');
% System properties should be set up
props = java.lang.System.getProperties;
props.setProperty('mail.smtp.auth','true');
props.setProperty('mail.smtp.socketFactory.class',
'javax.net.ssl.SSLSocketFactory');
props.setProperty('mail.smtp.socketFactory.port','465');

% Actually sending the email...