Hi,
I am reading string data of this format from a text file:
(20:200,40:300)
This is the area of an image which I wish to select. How do I convert this string to number range. Thanks.
Charles-

 採用された回答

Titus Edelhofer
Titus Edelhofer 2011 年 12 月 7 日

1 投票

Hi Charles,
a simple way would be replace all non digits by spaces and use str2num afterwards:
x = '(20:200,40:300)';
x(~isstrprop(x, 'digit')) = ' ';
xNumber = str2num(x)
Titus

12 件のコメント

Charles
Charles 2011 年 12 月 7 日
Thanks for your response. But this only extracts all the numbers present.
Titus Edelhofer
Titus Edelhofer 2011 年 12 月 7 日
That's right. But I guess xNumber(1):xNumber(2) and xNumber(3):xNumber(4) are what you are needing, aren't you?
Charles
Charles 2011 年 12 月 7 日
yes, but the numbers could vary, i.e. 4, 47...I have to process large amount of files. Thanks for your suggestions.
Titus Edelhofer
Titus Edelhofer 2011 年 12 月 7 日
Charles, I don't understand. Of course they can vary: take another x (read from your file) and you will get other numbers ...??
Charles
Charles 2011 年 12 月 7 日
Ok, first of all, xNumber = str2num(x) gives a single number. How do you grab the individual elements of the number? xNumber(1) wouldn't return the first number.
Secondly, assuming that it does work and using the above as an example. xNumber(1) returns 2. What if the first number is 20 instead, or 202? Hope you understand.
Sean de Wolski
Sean de Wolski 2011 年 12 月 7 日
A note: you can also use RESHAPE to reshape the numbers if there are multiples.
Titus Edelhofer
Titus Edelhofer 2011 年 12 月 7 日
Hi Charles, weird. When I run my code above I get a vector xNumber=[20 200 40 300] ...
Sean de Wolski
Sean de Wolski 2011 年 12 月 7 日
me too (2011b)
Charles
Charles 2011 年 12 月 7 日
Wow, unbelievable. Thanks a lot. The error that I made is that instead of x(~isstrprop(x, 'digit')) = ' ';
I typed x(~isstrprop(x, 'digit')) = '';
i.e, no space between the ''. I had to type as the matlab is running on another pc. Answer accepted. Thanks a million.
Titus Edelhofer
Titus Edelhofer 2011 年 12 月 7 日
;-) At least it proved worth doing what I once read from some other poster: please keep on asking and accept only when the question is fully answered...
Charles
Charles 2011 年 12 月 7 日
:-) I truly appreciate your assistance. Really, thanks a lot.
Andrei Bobrov
Andrei Bobrov 2011 年 12 月 7 日
str2double(regexp(x,'\d+','match'))

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

その他の回答 (1 件)

osman
osman 2011 年 12 月 7 日

0 投票

use str2num

2 件のコメント

Sean de Wolski
Sean de Wolski 2011 年 12 月 7 日
That won't work. He'd going to need to parse the string based on '(,:' first
Charles
Charles 2011 年 12 月 7 日
As Sean de Wolski pointed out, it doesn't work.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by