Making cell array of cells of strings the same size by adding empty strings

조회 수: 5 (최근 30일)
Hello,
Could someone please help me with the following:
I have a cell array of cells containing strings. The cells withing the cells have different length. I would like to write an empty string '' to make all the cells the same size.
Cell array of cells of string example:
c = {{'a1', 'B20', 'd_3'}; {'b44', 'C5', 'e_12', 'k234'}; {'a8', 'T565', 'V-d3'}; {'b44', 'C5', 'e_12', 'k234', 'k234', 'k234'}};
c =
4×1 cell array
{1×3 cell}
{1×4 cell}
{1×3 cell}
{1×6 cell}
len = cellfun('length', c)
len =
3
4
3
6
I need all the cells in c to be the same length, ie of length max(len) which is 6. I would like to add empty Strings '' from the last value to the 6th columns for all the cells that have a length that is less than 6.
so I would like to transform c into a cNew that would look like this this:
cNew = {{'a1', 'B20', 'd_3', '', '', ''}; {'b44', 'C5', 'e_12', 'k234', '', ''}; {'a8', 'T565', 'V-d3', '', '', ''}; {'b44', 'C5', 'e_12', 'k234', 'k234', 'k234'}};
cNew =
4×1 cell array
{1×6 cell}
{1×6 cell}
{1×6 cell}
{1×6 cell}
len = cellfun('length', cNew)
len =
6
6
6
6
If anyone could help I would be very grateful, thank you.
Best Regards;
Cecile

채택된 답변

Guillaume
Guillaume 2020년 1월 6일
maxlen = max(cellfun(@numel, yourcellarray));
newcellarray = cellfun(@(s) [s, repmat({''}, 1, maxlen - numel(s))], yourcellarray, 'UniformOutput', false);
would be one way.
  댓글 수: 2
Cecile
Cecile 2020년 1월 6일
Thank you very much, that's exactly it.
Dora Schuller
Dora Schuller 2021년 10월 15일
편집: Dora Schuller 2021년 10월 15일
Hi @Guillaume, thanks, it worked for me too. I would like to use the cell2table function, but I still get the result that my table contains only rows of {1x2 cell}.
So I had a similar input as in the question above:
z = {{{'a'}}
{{'b'} {'c'}}}
z =
2×1 cell array
{1×1 cell}
{1×2 cell}
Using your code, I got this, which looks good:
newcellarray =
1×2 cell array
{1×2 cell} {1×2 cell}
When I do cell2table:
>> cell2table(z)
ans =
2×1 table
z
__________
{1×1 cell}
{1×2 cell}
And I would like to convert it to a table like this:
var1 var2
'a' ''
'b' 'c'

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by