Effacer les filtres
Effacer les filtres

Why does table creation produce error "VariableNames property must contain one name for each variable in the table"?

160 vues (au cours des 30 derniers jours)
Can you please revise the following line of code to eliminate the error "VariableNames property must contain one name for each variable in the table"? I am stumped.
T = table(rand(30,8), 'VariableNames', ...
{'var1' 'var2' 'var3' 'var4' 'var5' 'var6' 'var7' 'var8'});

Réponse acceptée

KAE
KAE le 16 Jan 2017
Modifié(e) : KAE le 17 Jan 2017
Just figured this out: have to use array2table,
T = array2table(rand(30,8), ...
'VariableNames', {'var1' 'var2' 'var3' 'var4' 'var5' ...
'var6' 'var7' 'var8'});
However if you want to assign other properties besides names, you have to do that separately, unlike the table command,
T.Properties.VariableUnits = {'kg' 'm' 'W' 's' 'g' 'kg' 'm' 'W'};
  3 commentaires
Steven Lord
Steven Lord le 31 Jan 2024
Another MATLAB oddity to add to the list of annoyances/inconsistencies.
It's not an inconsistency.
When you call table like that, you're asking MATLAB to create a table with one variable, not eight. That one variable happens to contain eight columns. As a smaller example, here's a table with one variable that contains a two-column matrix. Note that the size of T1 is [5 1] not [5 2].
X = randi(10, 5, 2);
T1 = table(X, VariableNames = "Coordinates")
T1 = 5×1 table
Coordinates ___________ 2 5 9 8 9 2 7 7 3 8
size(T1)
ans = 1×2
5 1
When you use array2table instead, MATLAB creates one variable per column of the input. The size of T2 is [5 2].
T2 = array2table(X, VariableNames = ["X coordinate", "Y coordinate"])
T2 = 5×2 table
X coordinate Y coordinate ____________ ____________ 2 5 9 8 9 2 7 7 3 8
size(T2)
ans = 1×2
5 2

Connectez-vous pour commenter.

Plus de réponses (1)

Ivy Fatima
Ivy Fatima le 31 Jan 2024
Error using array2table
The RowNames property must contain one name for each row in the table.

Catégories

En savoir plus sur Tables dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by