MATLAB Answers

0

Extracting numeric values from character array

Asked by MiauMiau on 16 Sep 2018 at 18:20
Latest activity Commented on by MiauMiau on 17 Sep 2018 at 5:39

Hi, I have a character array "coords" (containing 3D coordinates), which looks something like this:

val =

    '[ 48. -24.  48.]'
    '[ 50. -22.  58.]'
    '[ 48. -20.  50.]'

I would like to find the index of a specific coordinate, something like:

find(coords == [50 -22 58])

How do I do that? Transforming coords as follows:

coords_num = str2double(coordinates)

just leads to:

coords_num = NaN

  1 Comment

What is the output of

>> coords

?

Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 16 Sep 2018 at 20:18
Edited by Stephen Cobeldick on 16 Sep 2018 at 20:19
 Accepted Answer

This is easy with sscanf:

>> coords = ['[ 48. -24.  48.]';'[ 50. -22.  58.]';'[ 48. -20.  50.]';'[ 49. -23.  52.]']
coords =
[ 48. -24.  48.]
[ 50. -22.  58.]
[ 48. -20.  50.]
[ 49. -23.  52.]
>> mat = reshape(sscanf(coords.','[%f%f%f]'),3,[]).' % convert to numeric
mat =
   48  -24   48
   50  -22   58
   48  -20   50
   49  -23   52
>> idx = all(mat==[50,-22,58],2) % match row
idx =
  0
  1
  0
  0
>> find(idx)
ans = 2

  1 Comment

Amazing, thanks!!

Sign in to comment.


Answer by Walter Roberson
on 16 Sep 2018 at 18:58

T = regexp( regexprep(coordinates, '\[|\]', ''), 'split') ;
coords_num = str2double(T) ;

  3 Comments

Thank you very much, but I get this error:

T = regexp( regexprep(coordinates, '\[|\]', ''), 'split') ;
Error using regexprep
The 'STRING' input must be either a char row vector, a cell array of char row vectors, or
a string array.

Why is that? If its of any help, it says "2092 x 16 char" (2092 coordinates stored).

Use cellstr(coordinates) where I had coordinates()

Thank you - just for others to know: I tried using cellstr on coordinates, but that let to an empty array T. The answer of Stephen works however - many thanks to both

Sign in to comment.