Cell arrays and strings in Matlab

Suppose you want to create a dynamic matrix of strings in Matlab.  For example, you might want the legend of your graph to depend on the data (which changes on a daily basis).  Cell arrays are your best bet.  However, be warned on how to access the elements of said arrays.  Suppose I have a cell array constructed as follows:

names = cell(3,2);
names(high_regime,: ) = [{'Probability of a home run'} {'Home Run'}];
names(low_regime, : ) = [{'Probability of bankruptcy'} {'Bankruptcy'}];
names(middle_regime, : ) = [{'Probability break-even'} {'Break-even'}];

If you want to access a particular element of this cell array as a string, you must use the curly brackets like so:

set(plot1(1),'LineStyle','-.','DisplayName',names{1,2});

If you try the standard names(1,2), the function set() will not think the result is a string.

Leave a Reply