mrjohnNY
mrjohnNY

Reputation: 3

how to get several numbers from a string in matlab

I'm struggling with getting numbers out of several strings:

'L/22P/93'
'P/8P/48L/3'
'1L/63P/751' (this one is: 1, 63, 75, 1)
'PL/18'
'P/30P/5'
'PP'

I want to get all numbers, so I can use them for calculation.

I have tried using regexp, but I can only get the first number of each string.

Upvotes: 0

Views: 180

Answers (3)

user2271770
user2271770

Reputation:

One easy way would be to replace all other characters with spaces, then read the string:

function nums = read_numbers(str)
        %// This works only for integer numbers without sign

        not_digit = (str < '0') | (str > '9');
        str(not_digit) = ' ';
        nums = sscanf(str, '%u');
end

As the comment says, the function doesn't take in account signs (+/-), the decimal point or real numbers in scientific notation.

After saving the above code in the file read_numbers.m, you can use it then like in this example:

>> read_numbers('L/22P/93');
        22
        93

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112689

Let your data be defined as a cell array of strings:

s = {'L/22P/93'
     'P/8P/48L/3'
     '1L/63P/751'
     'PL/18'
     'P/30P/5'
     'PP'};

Then

y = regexp(s, '\d+', 'match'); %// cell array of cell arrays of strings
y = cellfun(@str2double, y, 'uniformoutput', 0); %// convert to cell array of vectors

gives the result as a cell array of vectors:

y{1} =
    22    93
y{2} =
     8    48     3
y{3} =
     1    63   751
y{4} =
    18
y{5} =
    30     5
y{6} =
     []

Upvotes: 1

sco1
sco1

Reputation: 12214

While regular expressions can be intimidating, MATLAB's regex documentation is fairly comprehensive and should be sufficient to help solve this problem.

As others have commented there are a couple questions here that need to be answered in order to provide a comprehensive answer to your question:

  1. What code have you tried so far that only yields the first number? As @michael_0815 states, the simplest regex call returns the indices to all of the numbers in the string.
  2. What is your criteria for a number? Specifically in your third string you say there are 4 number groups when there are only 3. Do you only want a maximum grouping of 2 digits? This affects how the regex is structured.

In the meantime this should return what you've requested using regex, though it assumes your numbers are unsigned integers and you want a maximum grouping of 2 digits.

teststr = '1L/63P/751';
test = str2double(regexp(teststr, '\d{1,2}', 'match'));

Which returns the following array:

test =

 1    63    75     1

I would recommend playing around with an online regex tester to see how your inputs affect the results. My favorite is regex101. It's geared for other languages but the MATLAB syntax is similar enough for the most part.

Upvotes: 1

Related Questions