create a cell array of strings matlab

22,160

Solution 1

You need to do:

data = {'1';'2';'3';'4';'5';'6';'7';'8';'9';'10';'11';'12';'13';'14';'15';'16';'17';'18';'19';'20';};

Use {}. These will form a cell array.

Solution 2

You can use {} instead of [] to build a cell, or you can use strsplit to build an arbitrary length cell of strings representing numbers from 1 to N:

data = strsplit(num2str(1:N));

Update: The fastest way to do this now is with the undocumented sprintfc function (note the "c" at the end) which prints each element to it's own cell:

>> A = sprintfc('%g',1:20)
A = 
  Columns 1 through 11
    '1'    '2'    '3'    '4'    '5'    '6'    '7'    '8'    '9'    '10'    '11'
  Columns 12 through 20
    '12'    '13'    '14'    '15'    '16'    '17'    '18'    '19'    '20'
>> which sprintfc
built-in (undocumented)
Share:
22,160
brucezepplin
Author by

brucezepplin

Updated on August 25, 2020

Comments

  • brucezepplin
    brucezepplin over 3 years

    Hi I am trying to create a cell array of strings with:

    data = ['1';'2';'3';'4';'5';'6';'7';'8';'9';'10';'11';'12';'13';'14';'15';'16';'17';'18';'19';'20';];
    

    where I expecting a cell array of 25 elements. but I get:

    length(data)
    
    = 33
    

    so obviously numbers 12,13 etc are counting as 2 bits.

    My question is then how do I ensure the cell array is of length 20? also the function I am putting the cell array into has to be a cell array of strings even though I am using ints!

  • chappjc
    chappjc over 10 years
    @GuntherStruyf: Close! That doesn't give strings. I think you meant data=arrayfun(@num2str,1:N,'uni',false). ;)
  • chappjc
    chappjc over 10 years
    or cellfun(@num2str,num2cell(1:N),'uni',false). So many possibilities!
  • Gunther Struyf
    Gunther Struyf over 10 years
    @chapjc indeed, I forgot the num2str, I use that a lot for quickly putting numbers in a legend. But for your second option: that would be a step too much, there is no need for the num2cell since arrayfun just takes a normal array. The strsplit might be nicer (short and clear) actually now I look at it again
  • Benyamin Noori
    Benyamin Noori over 7 years
    Sir, you saved me from eternal misery. Thank you.