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

New to MATLAB?

How to convert strings to a matrix

Asked by Samira

Samira (view profile)

on 21 Nov 2012

I'm trying to convert strings to a matrix E.g Hello world would be [hello, world]

I have a .m file, and I'm able to read my strings but I don't know how to convert them. Can someone help me.

0 Comments

Samira

Samira (view profile)

Products

No products are associated with this question.

4 Answers

Answer by Azzi Abdelmalek

Azzi Abdelmalek (view profile)

on 21 Nov 2012
Accepted answer

This code takes in account more then one blanck space

s='Hello  world'
s1=regexp(s,' ','split'); 
out=s1(~cellfun(@isempty ,s1))

0 Comments

Azzi Abdelmalek

Azzi Abdelmalek (view profile)

Answer by Image Analyst

Image Analyst (view profile)

on 21 Nov 2012

They already are arrays, as I'm sure you probably just found out:

s = 'Hello World'
firstWord = s(1:5) % Extract elements of the array

0 Comments

Image Analyst

Image Analyst (view profile)

Answer by Thomas

Thomas (view profile)

on 21 Nov 2012

You could also try

in='Hello World'
splitstring = textscan(in,'%s');
out=splitstring{:}'

0 Comments

Thomas

Thomas (view profile)

Answer by Jan Simon

Jan Simon (view profile)

on 21 Nov 2012

Note that matrices of type char are padded by spaces. The string 'Hello world' contains a space in the middle. Does this disappear in ['Hello'; 'world']? And if so, how do you want to control this explicitly?

Str = 'This is a sentencte with word separated by spaces';
CStr = regexp(Str, ' ', 'split');
% >> CStr = {'This'; 'is'; 'a'; ...}
CharMatrix = char(CStr);
% >> CharMatrix = 
   ['This     '; ...
    'is       '; ...
    'a        '; ...
    'sentencse'; ...

Usually working with cell strings is more efficient.

0 Comments

Jan Simon

Jan Simon (view profile)

Contact us