MATLAB Answers

Variable name in a table with a space in it

161 views (last 30 days)
how can I create a variable name in a table with a space character inside?
When I use
table(data,'RowNames',{'Row1'},'VariableNames',{'Variable X'})
I get the error message
'Variable X' is not a valid name.
How can I circumvent that?

Accepted Answer

Image Analyst
Image Analyst on 24 Sep 2014
No. I don't know of any languages that can take spaces in variable names. The usual workaround is to use a different character, often an underline or dash.
Image Analyst
Image Analyst on 24 Sep 2014
Right. If you want, you could keep a separate array of strings, a cell array, with "friendly" names that use characters not allowed in variables of field/member names. See, but of course the bookkeeping might be cumbersome.

Sign in to comment.

More Answers (1)

Francesco Tricarico
Francesco Tricarico on 23 Oct 2020
Let me add some tips in addition to the Image Analyst accurate answer. I hope the following will help someone (working on a R2019b).
MATLAB R2019b accepts variable spaced names but it returns an error trying to access the variable directlty from the Variables tab in the GUI. For example both variables of this table
T = table({ones(8)},{1},'VariableNames',["variable 1", "variable 2"]);
are shown in the Variables tab:
Clicking on variable 2, the variable is not visible:
By the way, the variable content is in memory and becomes visible in the Command Window, prompting
i.e. accessing to the table cell with cell access method (MATLAB use structure access method when clicking on a table cell in the Variables tab).
A poor workourand is avoiding spaces and using Variable Descriptions (well documented in the official help) table property:
T = table({ones(8)},{1},'VariableNames',["variable_1", "variable_2"]);
T.Properties.VariableDescriptions = ["variable 1", "variable 2"];


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!