3

I want to generate a table but want to set the variable name of only one variable but want all other variables to keep their name.

Example, say I have this data:

User1 = rand(5,1);
User2 = rand(5,1);
User3 = rand(5,2);

I can now make the table using:

table(User1 , User2 , User3(:,1))

This gives me this:

ans = 

 User1       User2        Var3  
________    ________    ________

 0.55229    0.049533     0.14651
 0.62988     0.48957     0.18907
0.031991     0.19251    0.042652
 0.61471     0.12308      0.6352
 0.36241     0.20549     0.28187

I want to get this:

ans = 

 User1       User2        User3  
________    ________    ________

 0.55229    0.049533     0.14651
 0.62988     0.48957     0.18907
0.031991     0.19251    0.042652
 0.61471     0.12308      0.6352
 0.36241     0.20549     0.28187

I tried to do this:

table(User1 , User2 , User3(:,1), 'VariableNames',{'','','User3'} )

But this gives error:

Error using setVarNames (line 33)
The VariableNames property must be a cell array, with each element containing one nonempty
string.

Error in table (line 305)
            t = setVarNames(t,vnames); % error if invalid, duplicate, or empty

How do I solve my problem with MATLAB 2014b?

For my data, d is generated and table is made in a loop and I want to keep all the values of d. If this matters somehow.

EkEhsaas
  • 93
  • 9
  • 2
    See: [Change a Variable Name](https://www.mathworks.com/help/matlab/matlab_prog/modify-units-descriptions-and-table-variable-names.html#zmw57dd0e25360) or [Access and Modify Properties](https://www.mathworks.com/help/matlab/ref/tableproperties.html) – sco1 Dec 06 '16 at 17:42

2 Answers2

5

Per MATLAB's documentation for the table data type, you can accomplish this by modifying your table's VariableNames property.

Using the example table T:

T = table(rand(3, 1), rand(3, 1), rand(3, 1));

You can index variables numerically:

T.Properties.VariableNames{2} = 'Middle_Column' 
T.Properties.VariableNames(2:3) = {'Middle_Column', 'End_Column'} 

Or you can use table's implicit string comparison to index with a string:

T.Properties.VariableNames{'Var2'} = 'Middle_Column'
T.Properties.VariableNames({'Var2', 'Var3'}) = {'Middle_Column', 'End_Column'}

Or you can reassign the whole thing:

T.Properties.VariableNames = {'Start_Column', 'Middle_Column', 'End_Column'}
sco1
  • 12,154
  • 5
  • 26
  • 48
-3

table(User1 , User2 , User3(:,1),'VariableNames', {'User1', 'User2', 'User3'})

Leo
  • 22
  • 2
  • That's not what I wanted. You basically renaming all the variables. I wanted to rename only one variable, but thanks anyway – EkEhsaas Dec 06 '16 at 17:51