MATLAB Answers

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

조회 수: 2(최근 30일)
Aaron Devanathan
Aaron Devanathan 2021년 4월 9일
답변: Scott MacKenzie 2021년 5월 13일
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
Abhishek Gupta
Abhishek Gupta 2021년 4월 12일
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];

댓글을 달려면 로그인하십시오.

채택된 답변

Scott MacKenzie
Scott MacKenzie 2021년 5월 13일
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'}

추가 답변(0개)

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by