How to convert a string of characters to numbers?

I have the following string obtained from a text file (the text file has a lot of info so I had to go and look for certain lines):
0 0 0 0 0.1 0 0 0 BlaBla
Another line might look like this
1 0.013 0.0156 -0.104 0.0376 0.0624 0.132 0.132 BlaBlaBla
By the way I'm reading the file everything is now a string of characters.
How can I convert that to a vector? Notice that the last column is a string of characters. The white spaces on the first line is different than on the second one too.
Any help is appreciated thanks.

 採用された回答

Matt Fig
Matt Fig 2012 年 9 月 28 日
編集済み: Matt Fig 2012 年 9 月 28 日

0 投票

str = '1 0.013 0.0156 -0.104 0.0376 0.0624 0.132 0.132 Bla';
T = regexp(str,'-*\d*\.*\d*','match');
V = cellfun(@str2double,T)

7 件のコメント

Matt Fig
Matt Fig 2012 年 9 月 28 日
編集済み: Matt Fig 2012 年 9 月 28 日
carlos Uribe comments:
"Thanks Matt that works when I have just one string...
Now my problem is that I have a cell of those strings (cell).
T = regexp(cell,'-*\d*\.*\d*','match');
works fine and gives me a cell T with many cells
V = cellfun(@str2double,T)
gives me a problem because I cannot input a cell there...
Any workarounds for this?"
Matt Fig
Matt Fig 2012 年 9 月 28 日
Yes, just do the same for each element of T.
str = {'1 0.013 0.0156 -0.104 0.0376 0.0624 0.132 0.132 Bla'};
str(2) = {'22 0 3 0 0.1 0 0 0 BlaBla'};
T = regexp(str,'-*\d*\.*\d*','match');
V = cellfun(@str2double,T,'Un',0);
V{1}
V{2}
carlos Uribe
carlos Uribe 2012 年 9 月 28 日
I was just trying to figure out if there was kind of a "vectorized" way of doing it...given that right now I have 10^8 of those strings.
Matt Fig
Matt Fig 2012 年 9 月 28 日
You mean more vectorized than I showed above? How could it be more vectorized than what I showed above, since there are no MATLAB loops?
Jan
Jan 2012 年 9 月 28 日
V = str2double(T); % Without CELLFUN
carlos Uribe
carlos Uribe 2012 年 9 月 28 日
My bad..didn't see that you added two new values to cellfun...thanks for your help
Matt Fig
Matt Fig 2012 年 9 月 28 日
Jan, that returns nans here...

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2012 年 9 月 28 日

0 投票

str = '1 0.013 0.0156 -0.104 0.0376 0.0624 0.132 0.132 Bla';
V = sscanf(str, '%g', 6);

1 件のコメント

Matt Fig
Matt Fig 2012 年 9 月 28 日
Or for cell str:
V = cellfun(@(x) sscanf(x, '%g'),str,'Un',0);
Very nice... no call to REGEXP.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File Exchange で Characters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by