Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Moving characters from a string into a cell array

Subject: Moving characters from a string into a cell array

From: John

Date: 18 Feb, 2012 22:48:11

Message: 1 of 7

I am trying to find a way to separate all of the characters from a sting and save them to a cell array within a larger cell array of the words. For example "Hello how are you?" would become {{"H","e","l","l","o"}, {"h","o","w"}, {"a","r","e"} ,{"y","o","u"}}. Each letter has it's own cell within an array and each word is a cell within a master array. I hope that makes sense. If anyone can help out I'd appreciate it because I've been cracking at this for a couple days and I cannot figure it out.

Respectfully,

John

Subject: Moving characters from a string into a cell array

From: Sadik

Date: 18 Feb, 2012 23:52:11

Message: 2 of 7

Hi John,

One solution:

s = 'Hello how are you';
c = textscan(s,'%s');
c = c{1};
for k = 1:length(c)
    c{k} = cellstr(c{k}')';
end

Best.

Subject: Moving characters from a string into a cell array

From: ImageAnalyst

Date: 19 Feb, 2012 00:07:27

Message: 3 of 7

A simple way:

for k = 1:length(s)
  ca{k} = s(k)
end

Subject: Moving characters from a string into a cell array

From: ImageAnalyst

Date: 19 Feb, 2012 00:10:40

Message: 4 of 7

On Feb 18, 7:07 pm, ImageAnalyst <imageanal...@mailinator.com> wrote:
> A simple way:
>
> for k = 1:length(s)
>   ca{k} = s(k)
> end

Sorry - didn't read closely enough. It looks like Sadik's way will do
it.

Subject: Moving characters from a string into a cell array

From: james bejon

Date: 19 Feb, 2012 01:18:35

Message: 5 of 7

s = regexp(regexp('Hi! How are you?', '\w+', 'match'), '\w', 'match')

Subject: Moving characters from a string into a cell array

From: Bruno Luong

Date: 19 Feb, 2012 08:30:17

Message: 6 of 7

Without regular expression:

s='Hello how are you'

b = [true s==' '];
b(end) = true;
lgt = diff(find(b));
c=mat2cell(num2cell(s),1,lgt)

c{:}

You can adapt to remove the space character.

% Bruno

Subject: Moving characters from a string into a cell array

From: John

Date: 19 Feb, 2012 15:06:10

Message: 7 of 7

Thanks for the help everyone. The code works great.

John

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us