confusing error while using Table

14 views (last 30 days)
I am trying to make a simple table so that I can access some data by using names instead of a numeric index of a cell.
locationsTable = table(splitLocations, 'VariableNames', headerNames);
headerNames = {'rawData', 'testConfig', 'efiData', 'bonusData'};
splitLocations = {2, 49, 74, 142};
However, when I try to run this, I get the error
Error using setVarNames (line 35) The VariableNames property must contain one name for each variable in the table.
Error in table (line 304) t = setVarNames(t,vnames); % error if invalid, duplicate, or empty
This is confusing me, since I have a name for each variable, and none of them are invalid, duplicate or empty. I am unsure what I am doing wrong and what I need to change so that it works. Any help would be appreciated.

Accepted Answer

Sean de Wolski
Sean de Wolski on 4 Aug 2015
locationsTable = table(splitLocations{:}, 'VariableNames', headerNames);
It's seeing splitLocations as one variable, not four. Two have it see each scalar as a separate value, use comma-separated list expansion to pass in all four inputs as scalars.
  1 Comment
Peter Perkins
Peter Perkins on 5 Aug 2015
Or use cell2table:
>> cell2table(splitLocations,'VariableNames',headerNames)
ans =
rawData testConfig efiData bonusData
_______ __________ _______ _________
2 49 74 142
A cell array is (in this context) just like any other MATLAB variable: if you pass one variable into table, you get a table with one variable (although in your case of course you got an error because you had four names). And what's more, because splitLocations was 1x4, you would have gotten a table containing one variable that itself had four columns. In other words, this
>> table(splitLocations)
ans =
splitLocations
______________
[1x4 cell]
is perfectly legal, it just probably isn't what you wanted.

Sign in to comment.

More Answers (0)

Categories

Find more on Preprocessing Data in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!