Concatenate cell with numeric array in tables
조회 수: 7 (최근 30일)
이전 댓글 표시
I have a ridiculously simple problem that I cannot solve. I have two tables and I want to concatenate them, but one contains a column with a cell array and one with a numeric array.
a = table([1; 2; 3]);
b = table({[1 2]; [3 4]})
c = [a; b];
This immediately produces an error because I am trying to concatenate a cell with a non-cell type. But if I just try to concatenate these variables outside a table, it works fine, recognizing that the result should be a cell array. There seems to be no way of telling matlab that I want it to convert a's variable to a cell array.
The actual problem is somewhat more complex - it's easy enough to solve this in the current case by just removing the variables from the table and concatenating them, then making a new table. But in the actual use case the tables have up to 50 variables, and it's unknown at runtime which of them are causing the problem.
Suggestions?
댓글 수: 0
채택된 답변
Robert U
2019년 10월 30일
Hi Marcus Watson,
an straight-forward solution would be checking the variable types stored in the table. In case they don't match change the numerical one to cell array.
a = table([1; 2; 3]);
b = table({[1 2]; [3 4]})
if ~cellfun(@isempty,{a{:,vartype('numeric')}}) && cellfun(@isempty,{b{:,vartype('numeric')}})
a = table({a{:,vartype('numeric')}});
elseif cellfun(@isempty,{a{:,vartype('numeric')}}) && ~cellfun(@isempty,{b{:,vartype('numeric')}})
b = table({b{:,vartype('numeric')}});
end
c = [a; b];
In case there are anyway no numerical values to concatenate you can change all tables that are containing numerical values to cells.
Kind regards,
Robert
댓글 수: 5
Robert U
2019년 10월 30일
a = table([1; 2; 3]);
b = table({[1 2]; [3 4]});
if cellfun(@isempty,{a{:,vartype('cell')}}) && ~cellfun(@isempty,{b{:,vartype('cell')}})
a = table(num2cell(a{:,vartype('numeric')}));
elseif ~cellfun(@isempty,{a{:,vartype('cell')}}) && cellfun(@isempty,{b{:,vartype('cell')}})
b = table(num2cell(b{:,vartype('numeric')}));
end
c = [a; b];
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!