I would like to extract integers from strings from a cell array in Matlab. Each string contains 1 or 2 integers formatted as shown below. Each number can be one or two digits. I would like to convert each string to a 1x2 array. If there is only one number in the string, the second column should be -1. If there are two numbers then the first entry should be the first number, and the second entry should be the second number.
'[1, 2]'
'[3]'
'[10, 3]'
'[1, 12]'
'[11, 12]'
Thank you very much!
I have tried a few different methods that did not work out. I think that I need to use regex and am having difficulty finding the proper expression.
You can use
str2numto convert well formatted chars (which you appear to have) to the correct arrays/scalars. Then simply pad from theend+1element to the 2nd element (note this is nothing in the case there's already two elements) with the value-1.This is most clearly done in a small loop, see the comments for details:
If you really wanted to use regex, you could replace the loop part with something similar:
But there are lots of ways to do this without touching regex, for example you could
erasethe square brackets, split on a comma, and pad with-1according to whether or not there's a comma in each row. Wrap it all in a much harder to read (vs a loop)cellfunand ta-dah you get a one-liner:I'd recommend one of the loops for ease of reading and debugging.