brucezepplin
brucezepplin

Reputation: 9752

create a cell array of strings matlab

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!

Upvotes: 7

Views: 22361

Answers (2)

chappjc
chappjc

Reputation: 30579

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)

Upvotes: 11

JustinBlaber
JustinBlaber

Reputation: 4650

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.

Upvotes: 16

Related Questions