Matlab Tips

The following are some handy Matlab tricks,

1. You can import data directly from FRED using getFredData.m function I created.

  • Download getFredData.m (you can either put it in your active folder, or better yet add it to the Matlab path). [Github]
  • Now just import the series you want (here M1 money for period 1960 to 2000):
    M1 = getFredData(‘M1SL’, ‘1960-01-01’, ‘2000-12-31’)
  • This will give you a structure M1, the data series itself is in M1.Data(:,2).
  • The M1 structure also contains other info, eg. M1.Title, or the dates in M1.Data(:,1).
  • Dates are in Matlab’s datenum format, counts days starting from 0000-01-01. You can convert them using Matlab functions datestr and datevec, graph them with dateticks. Sometimes you will want them in a format telling you the quarter; use datevec, get months, and then turn months to quarters using ceil(‘month’/3).
  • More options: M1 is monthly by default, but we can ask for quarterly data (‘q’) and expressed as Percentage Change of Year Ago (‘pca’).
    M1 = getFredData(‘M1SL’, ‘1960-01-01’, ‘2000-12-31′,’pca’,’q’)
  • There are other, more advanced options in getFredData, including ALFRED historical data, either use Matlab help or read the m-file for details.
  • [Matlab has a built-in function fetch for accessing FRED, but it can’t change frequency or units. getFredData.m builds on an earlier version by Kim Ruhl]

2. You can create latex tables in Matlab, and then just import them into your document, this means they will be automatically updated. The following is a small example code (Stata offers the option to export results as latex):

This is the Matlab code to generate MyTable (you have to use \\ in matlab to type a single \).
%Uses data from DataMatrix (a 2×1) and ModelMatrix (2×1) just to give an idea.
FID = fopen(‘/home/MyTable.tex’, ‘w’);
fprintf(FID, ‘\\begin{tabular*}{lcc} \\hline \\hline \n’);
fprintf(FID, ‘ & \\multicolumn{2}{c}{1980} \\\\ \\hline \n’);
fprintf(FID, ‘ & Data & Model \\\\ \\hline \n’);
fprintf(FID, ‘Capital-Output ratio & %8.2f & %8.2f\\\\ \n’, DataMatrix(1), ModelMatrix(1));
fprintf(FID, ‘Fraction of time worked & %8.2f & %8.2f\\\\ \n’, DataMatrix(2), ModelMatrix(2));
fprintf(FID, ‘\\hline \\hline \n \\end{tabular*} \n’);

This is the latex code to bring in MyTable.
\caption{Table Containing Some Important Shit}

3. I recommend using to create graphs from Matlab. It gives much more control over graphs, as well as making nicer looking ones, and easily handles things like publishing graphs to the web, and saving them as jpg or pdf. If you master plotly’s graphing language (rather than creating matlab plots and then converting them) then you, or your collaborators, can also then just use plotly in R, Julia, Python, & Excel making it easy to share them among you.

4. A short list of commands I use to teach Intro to Matlab classes. Further Matlab example of how to simulate time series. Learn Matlab from Matlab Acadamy, including a 2hr ‘OnRamp’ intro.