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

12 views (last 30 days)
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

Accepted Answer

Guillaume
Guillaume on 6 Jan 2020
maxlen = max(cellfun(@numel, yourcellarray));
newcellarray = cellfun(@(s) [s, repmat({''}, 1, maxlen - numel(s))], yourcellarray, 'UniformOutput', false);
would be one way.
  2 Comments
Dora Schuller
Dora Schuller on 15 Oct 2021
Edited: Dora Schuller on 15 Oct 2021
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'

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!