Clear Filters
Clear Filters

Use table row as input for a new table

52 views (last 30 days)
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))

Accepted Answer

Kevin Holly
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"
table1 = 1×3 table
col1 col2 col3 ____ ____ ____ "x1" "x2" "x3"
table2 = table;
table2.col1 = "y1";
table2.col2 = "y2";
table2.col3 = "y3"
table2 = 1×3 table
col1 col2 col3 ____ ____ ____ "y1" "y2" "y3"
target_table=table;
target_table.col1 = table2array(table1(:,:))';
target_table.col2 = table2array(table2(:,:))'
target_table = 3×2 table
col1 col2 ____ ____ "x1" "y1" "x2" "y2" "x3" "y3"
See below if you start off with vector arrays:
table1 = table2array(table1)
table1 = 1×3 string array
"x1" "x2" "x3"
table2 = table2array(table2)
table2 = 1×3 string array
"y1" "y2" "y3"
target_table=table;
target_table.col1 = table1';
target_table.col2 = table2'
target_table = 3×2 table
col1 col2 ____ ____ "x1" "y1" "x2" "y2" "x3" "y3"

More Answers (1)

Steven Lord
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'})
T = 3×2 table
Var1 Var2 ____ ____ 0 0 0 0 0 0
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).'
T = 3×2 table
Var1 Var2 ____ ____ 1 4 2 5 3 6

Products

Community Treasure Hunt

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

Start Hunting!