필터 지우기
필터 지우기

Convert nested text cell array

조회 수: 2 (최근 30일)
Dora Schuller
Dora Schuller 2021년 10월 14일
댓글: Dora Schuller 2021년 10월 19일
Hi,
I have a nested text cell array of different lengths. I would like to make a table from them.
myarray = {{{'a'}}
{{'b'} {'c'}}}
myarray =
2×1 cell array
{1×1 cell}
{1×2 cell}
maxlen = max(cellfun(@numel, myarray));
newcellarray = cellfun(@(s) [s, repmat({''}, 1, maxlen - numel(s))], myarray, 'UniformOutput', false);
I got this:
newcellarray =
1×2 cell array
{1×2 cell} {1×2 cell}
When I do array2table:
array2table(newcellarray)
ans =
2×1 table
newcellarray
____________
{1×2 cell}
{1×2 cell}
But I would like to get something like:
var1 var2
'a' ''
'b' 'c'
Alternatively, if every row of the cell array would be converted to a python-list like structure, it would be even better:
['a', '']
['b', 'c']
Even better if every list would be different size:
['a']
['b', 'c']
  댓글 수: 2
Stephen23
Stephen23 2021년 10월 16일
편집: Stephen23 2021년 10월 16일
"if every row of the cell array would be converted to a python-list like structure,"
A python list is basically the same as a MATLAB cell array (i.e. mutable container class), so it is not clear how what you are requsting would be any different from what you show.
MATLAB does not have a "list" type, your examples use the concatenation operator to concatenate character arrays.
Dora Schuller
Dora Schuller 2021년 10월 19일
I see, thanks for the answer. I just wanted to convert it to a human readable format, which displays what is exactly inside the cells. But the answer below worked.

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

채택된 답변

DGM
DGM 2021년 10월 15일
I'm sure there's a simpler way, but idk.
This will convert to a table. Note that the table columns are cell vectors. This is the normal behavior of cell2table, and is necessary as the alternative would be a char column vector with empty elements -- something which can't exist, as arrays can't have holes in them.
myarray = {{{'a'}}
{{'b'} {'c'}}};
maxlen = max(cellfun(@numel, myarray));
newcellarray = cellfun(@(s) [s, repmat({{''}}, 1, maxlen - numel(s))], myarray, 'UniformOutput', false);
% if the inner cells are scalar:
newcellarray = vertcat(newcellarray{:});
newcellarray = cellfun(@(x) horzcat(x{:}),newcellarray,'uniform',false); % get rid of inner cells
T = cell2table(newcellarray)
T = 2×2 table
newcellarray1 newcellarray2 _____________ _____________ {'a'} {0×0 char} {'b'} {'c' }
I don't know anything about python, but I don't know why it wouldn't suffice to just get rid of the redundant nesting of the original cell array.
% alternative?
newcellarray2 = cellfun(@(x) horzcat(x{:}),myarray,'uniform',false); % get rid of inner cells
  댓글 수: 1
Dora Schuller
Dora Schuller 2021년 10월 19일
Thank you, this worked!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by