Convert table with many rows to table with single row with data in sequence

조회 수: 10(최근 30일)
What is an efficient way to assign values from one table (many rows and columns) to a table with one row.
Table 1: 3 variables with 10 entries each (10 rows x 3 columns) - VarNames: Start, End, Time & all values are numbers
Table 2: I want to extract data from Table 1 and input the values into Table 2 - VarNames: Start1, End1, Time1, Start2, End2, Time2, ... Start10, End10, Time10
For example:
The goal is to create something like below so that every column in Table2 doesn't need to have its own line of code; but I'm not sure if that's possible or realistic to do.
T2 = table();
x = 1;
while x<11
T2.Start(x) = T1(x,1);
T2.End(x) = T1(x,2);
T2.Time(x) = T1(x,3);
x = x+1;
end

채택된 답변

Cris LaPierre
Cris LaPierre 2022년 8월 17일
A bit convoluted, but should work.
% Create first table
Start = (11:10:101)';
End = Start+1;
Time = End+1;
T1 = table(Start,End,Time)
T1 = 10×3 table
Start End Time _____ ___ ____ 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53 61 62 63 71 72 73 81 82 83 91 92 93 101 102 103
% Turn table into an array and transpose
d = table2array(T1)'
d = 3×10
11 21 31 41 51 61 71 81 91 101 12 22 32 42 52 62 72 82 92 102 13 23 33 43 53 63 73 83 93 103
% create new variable names
varnm = ["Start";"End";"Time"] + (1:length(d));
% Build new table
T2 = array2table(d(:)','VariableNames',varnm(:))
T2 = 1×30 table
Start1 End1 Time1 Start2 End2 Time2 Start3 End3 Time3 Start4 End4 Time4 Start5 End5 Time5 Start6 End6 Time6 Start7 End7 Time7 Start8 End8 Time8 Start9 End9 Time9 Start10 End10 Time10 ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ ______ ____ _____ _______ _____ ______ 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53 61 62 63 71 72 73 81 82 83 91 92 93 101 102 103
  댓글 수: 3
Jasmyn Lee
Jasmyn Lee 2022년 8월 27일 15:21
Managed to merge this with my existing code and everything works. Thanks so much!

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

추가 답변(1개)

David Hill
David Hill 2022년 8월 17일
m=table2array(T1);

Community Treasure Hunt

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

Start Hunting!

Translated by