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

178 次查看(过去 30 天)
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'});

采纳的回答

KAE
KAE 2017-1-16
编辑:KAE 2017-1-17
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 个评论
Steven Lord
Steven Lord 2024-1-31
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

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by