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

4 次查看(过去 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 个评论
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 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by