How to convert strings to a matrix

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.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2012년 11월 21일

0 개 추천

This code takes in account more then one blanck space
s='Hello world'
s1=regexp(s,' ','split');
out=s1(~cellfun(@isempty ,s1))

추가 답변 (3개)

Image Analyst
Image Analyst 2012년 11월 21일

0 개 추천

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
Thomas
Thomas 2012년 11월 21일

0 개 추천

You could also try
in='Hello World'
splitstring = textscan(in,'%s');
out=splitstring{:}'
Jan
Jan 2012년 11월 21일

0 개 추천

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.

카테고리

도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by