Day 17: Two ways to get started with tables in MATLAB

Jozsef Meszaros
3 min readMay 23, 2020

--

On Day 16, I posted the “Ten Table Commandments” — a set of guidelines that I believe will help you quickly and effectively incorporate tables into your data analysis. Theory is great, and over time, people will develop their own intuitions based on a mix of advice and experience. Here are some examples of how to get started with tables in MATLAB while staying true to the “Ten Table Commandments”.

Scenario 1: You already have data to put into the table

We’ll generate some fake data to simulate the situation where you are making a table from data that already exists in your workspace. Here’s how it might look:

mylabels = categorical( [repmat( {'Mouse1'}, 5, 1 );repmat( {'Mouse2'}, 5, 1 )] )
mydata = rand(10,100);
mytable = table( mylabels, mydata, 'VariableNames',...                   {'Labels','Data'})

Scenario 2: You want to grow your table row by row

We’ll generate a table row by row. There are at least two good options for doing this, depending on whether you know how many rows you will have in your table. Let’s start with the first scenario where you don’t know how many rows you’ll have but you want to build up the table row by row.

mytable = table( [], [], [], 'VariableNames',...{'Subject','Treatment','Data'} )

Now to grow this table, you can simply use the semi-colon:

mytable = [mytable; ...
table( {'Mouse1'}, {'Control'}, rand(1,10),.. 'VariableNames', {'Subject','Treatment','Data'} )]

A work-around for having to name the variables each time is to omit them entirely from the definition of mytable, and then use this operation once your table is made:

mytable = table( [],[],[] );
mytable = [mytable; table({'Mouse1'},{'Control'},rand(1,10))];
mytable.Properties.VariableNames = {'Subject','Date','Treatment'};

Now for the situation where you know exactly what your table will look like, try this:

nrows = 10;
ncols = 2;
mytable = table( 'Size', [nrows,ncols],...
'VariableTypes', {'categorical','double'},...
'VariableNames', {'Name', 'Score'} )

If you found this a useful introduction to tables, go on to my post from Day 21 to see how we can have fun with tables, using MATLAB’s wonderful and rarely discussed varfun function.

--

--

Jozsef Meszaros
Jozsef Meszaros

No responses yet