Borrar filtros
Borrar filtros

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

178 visualizaciones (últimos 30 días)
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'});

Respuesta aceptada

KAE
KAE el 16 de En. de 2017
Editada: KAE el 17 de En. de 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 comentarios
Steven Lord
Steven Lord el 31 de En. de 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

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Más información sobre Tables en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by