MATLAB Answers

Adding a column of the same character name for all the rows in a table

2 views (last 30 days)
I have a table in MATLAB that I'd like to add a column that contains a character variable that's the same throughout the column, but different size lengths. Here's a code for two random tables.
Is there a way, for example, for me to add a column named 'Time' that contains the character 'hours' for both based on the number of rows of the table?
r1 = rand(100,1);
r1 = array2table(r1);
r1.Properties.VariableNames = {'Random1'};
r2 = rand(54,1);
r2 = array2table(r2);
r2.Properties.VariableNames = {'Random2'};
  1 Comment
Abhishek Gupta
Abhishek Gupta on 12 Apr 2021
Hi,
As per my understanding, you want to add a column to the existing table. You can do the same in the following way: -
r1 = rand(100,1);
r1 = array2table(r1);
r1.Properties.VariableNames = {'Random1'};
strs1 = repmat('hours', size(r1, 1), 1);
vTbl1 = table(strs1, 'VariableNames',{'Time'});
r1 = [r1, vTbl1];
r2 = rand(54,1);
r2 = array2table(r2);
r2.Properties.VariableNames = {'Random2'};
strs2 = repmat('hours', size(r2, 1), 1);
vTbl2 = table(strs2, 'VariableNames',{'Time'});
r2 = [r2, vTbl2];

Sign in to comment.

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 13 May 2021
From my understanding of the question, this is simply a matter of making the necessary assignment to r1.Time or r2.Time. Do so and a new column with variable name Time is automatically appended to the table:
r1 = rand(100,1);
r1 = array2table(r1);
r1.Properties.VariableNames = {'Random1'};
r1.Time = repmat({'hours'}, height(r1), 1);
r2 = rand(54,1);
r2 = array2table(r2);
r2.Properties.VariableNames = {'Random2'};
r2.Time = repmat({'hours'}, height(r2), 1);
Here's a command-window dump of the first 8 rows in the new r1:
>> head(r1)
ans =
8×2 table
Random1 Time
_________ _________
0.49707 {'hours'}
0.32079 {'hours'}
0.61628 {'hours'}
0.0068941 {'hours'}
0.062934 {'hours'}
0.92002 {'hours'}
0.90616 {'hours'}
0.83154 {'hours'}

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!