string to num

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-

 Accepted Answer

Titus Edelhofer
Titus Edelhofer on 7 Dec 2011
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 Comments

Charles
Charles on 7 Dec 2011
Thanks for your response. But this only extracts all the numbers present.
Titus Edelhofer
Titus Edelhofer on 7 Dec 2011
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 on 7 Dec 2011
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 on 7 Dec 2011
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 on 7 Dec 2011
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 on 7 Dec 2011
A note: you can also use RESHAPE to reshape the numbers if there are multiples.
Titus Edelhofer
Titus Edelhofer on 7 Dec 2011
Hi Charles, weird. When I run my code above I get a vector xNumber=[20 200 40 300] ...
Sean de Wolski
Sean de Wolski on 7 Dec 2011
me too (2011b)
Charles
Charles on 7 Dec 2011
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 on 7 Dec 2011
;-) 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 on 7 Dec 2011
:-) I truly appreciate your assistance. Really, thanks a lot.
Andrei Bobrov
Andrei Bobrov on 7 Dec 2011
str2double(regexp(x,'\d+','match'))

Sign in to comment.

More Answers (1)

osman
osman on 7 Dec 2011

0 votes

use str2num

2 Comments

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

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!