How to insert a n x m matrix or table, into an existing table?
조회 수: 26 (최근 30일)
이전 댓글 표시
Hello,
I would like to nest an n x m matrix into a table, by using a for loop to populate each row of the table with a corresponding matrix. I am running matlab 2018a. Below you can find example code:
% create the table
subject = [1; 2; 3; 4];
condition = {'cond1';'cond2';'cond3';'cond4'};
data = NaN(4,1);
T = table(subject,condition,data);
% populate the table with matrixes, using a for loop
for i = 1:1:size(T,1)
data = rand(10,5);
T.data(i) = data; % ERROR Unable to perform assignment because the left and right sides have a different number of elements.
end
I thought it was possible to create nested tables. However, I am not sure, on account of the error. I know tables within tables exists, but I am unsure whether you can nest a matrix/array in a table. Therefore, it is also allowed to transform the data matrix to a table, and then nest the table in the table. Of importance, I want to retain the for loop mechanism to populate the table.
Thanks in advance,
Jens
댓글 수: 1
Peter Perkins
2018년 12월 11일
Jens, it is definitely possible to put tables in tables, and (e.g. numeric) matrices in tables. There are two ways you might do that. The first is like this:
>> t = table(array2table(rand(5,2)),rand(5,2))
t =
5×2 table
Var1 Var2
Var1 Var2
__________________ __________________
0.81472 0.09754 0.15761 0.14189
0.90579 0.2785 0.97059 0.42176
0.12699 0.54688 0.95717 0.91574
0.91338 0.95751 0.48538 0.79221
0.63236 0.96489 0.80028 0.95949
The second is like this:
>> t = table({array2table(rand(2));array2table(rand(3));array2table(rand(4))},{rand(5);rand(6);rand(7)})
t =
3×2 table
Var1 Var2
___________ ____________
[2×2 table] [5×5 double]
[3×3 table] [6×6 double]
[4×4 table] [7×7 double]
These are two different storage schemes for two different kinds of data - in the first, each row of the inner table and matrix correspond to one row of the outer table, while in the second, each row of the outer table contains a table and a mtrix of different sizes. It sounds like you were looking for the second.
채택된 답변
Sean de Wolski
2018년 12월 10일
편집: Sean de Wolski
2018년 12월 10일
Sounds like data should be a cell array to which you insert 10x5 matrices.
replace:
data = cell(4,1);
And
T.data{i} = data;
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!