Use table row as input for a new table
52 views (last 30 days)
Show older comments
I would like to create a new table that has 2 columns. These columns are supposed to be filled with the values from the rows of 2 other tables. So basically:
target_table:
col1 col2
x1 y1
x2 y2
x3 y3
table1:
col1 col2 col3
x1 x2 x3
table2:
col1 col2 col3
y1 y2 y3
I was thinking something simple like this but I keep on getting errors of size mismatches or I ned up wit hthe values from the table becoming strings or cells:
target_table(:,"col1") = rows2vars(tail(table1,1))
0 Comments
Accepted Answer
Kevin Holly
on 16 Jun 2022
Are you starting off with vector arrays or tables? Note, below would also work if you used numeric values instead of strings.
See below if you start off with tables:
table1 = table;
table1.col1 = "x1";
table1.col2 = "x2";
table1.col3 = "x3"
table2 = table;
table2.col1 = "y1";
table2.col2 = "y2";
table2.col3 = "y3"
target_table=table;
target_table.col1 = table2array(table1(:,:))';
target_table.col2 = table2array(table2(:,:))'
See below if you start off with vector arrays:
table1 = table2array(table1)
table2 = table2array(table2)
target_table=table;
target_table.col1 = table1';
target_table.col2 = table2'
More Answers (1)
Steven Lord
on 16 Jun 2022
Let's make two sample tables.
T1 = array2table(1:3);
T2 = array2table(4:6);
Create a third table to hold the data from the first two. The "magic number" 2 in the line below comes from the fact that I know I'm combining two tables. If you're in a situation where you need that number to be dynamic and/or much larger than 2 that's a sign that you may want to rethink your approach and revise your code to avoid creating T1, T2, T3, T4, ...
T = table('size', [width(T1), 2], 'VariableTypes', {'double', 'double'})
Now assuming all the variables in T1 can be concatenated (with conversion, if necessary) you can use T1.Variables to extract all the data as an array. This array can be transposed and put into one of the variables in T. The same holds for T2.
T{:, 1} = (T1.Variables).';
T{:, 2} = (T2.Variables).'
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!