0

Suppose we have a 1x3 table A=table(1,2,3);

whose header names should contain a mix of numericals and non-numericals:

A.Properties.VariableNames={'from 1st-5th' 'from 6th-10th' ... 'from 11th-15th'};

and generates the following error:

from 1st-5th' is not a valid variable name.

I tried the sprintf function to solve this error, but the formatSpec parameter is confusing. Furthermore, I read about eval and would like to know whether it is helpful in my context.

Outcome of genvarname use:

enter image description here

hmofrad
  • 1,784
  • 2
  • 22
  • 28
John
  • 71
  • 7

1 Answers1

3

As your error very clearly states, the strings that you have provided for the variable names are not valid variable names when they have to be

Variable names, specified as a cell array of character vectors that are nonempty and distinct. Variable names must be valid MATLAB® variable names

You can use the built-in genvarname to convert your strings to valid variable names

A.Properties.VariableNames = genvarname({'from 1st-5th' 'from 6th-10th' 'from 11th-15th'});

Alternately, come up with your own variable names that are valid variable names (no spaces or hyphens).

names = {'from 1st-5th' 'from 6th-10th' 'from 11th-15th'};
A.Properties.VariableNames = regexprep(names, '[ \-]', '_');
Suever
  • 64,497
  • 14
  • 82
  • 101
  • thanks, @Suever! Unfortunately this didn't quite produce the desired outcome (see snapshot above) – John Jan 23 '17 at 23:18
  • @John If the output of `genvarname` doesn't work, then change the labels yourself so that they are what you want them to be (they have to be valid variable names). You can see the links I posted for what defined a valid name – Suever Jan 23 '17 at 23:21
  • thanks, @Suever! The work-around solution (e.g. "from_1st_5th") does its job for now, yet I am still looking for the actual outcome in the form as described above – John Jan 24 '17 at 08:32
  • @John it is not possible since those strings are not valid variable names – Suever Jan 24 '17 at 12:48
  • understood, @Suever! Thanks a lot – John Jan 24 '17 at 15:04