Azzera filtri
Azzera filtri

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

178 visualizzazioni (ultimi 30 giorni)
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'});

Risposta accettata

KAE
KAE il 16 Gen 2017
Modificato: KAE il 17 Gen 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 Commenti
Steven Lord
Steven Lord il 31 Gen 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

Accedi per commentare.

Più risposte (1)

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

Categorie

Scopri di più su Tables in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by