MATLAB Answers

Extracting numeric values from character array

63 views (last 30 days)
MiauMiau
MiauMiau on 16 Sep 2018
Commented: MiauMiau on 27 Sep 2018
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

Accepted Answer

Stephen
Stephen on 16 Sep 2018
Edited: Stephen on 16 Sep 2018
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
  7 Comments
MiauMiau
MiauMiau on 27 Sep 2018
Many thanks for all your time and help, that is really very helpful!

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 16 Sep 2018
T = regexp( regexprep(coordinates, '\[|\]', ''), 'split') ;
coords_num = str2double(T) ;
  3 Comments
MiauMiau
MiauMiau on 17 Sep 2018
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.

Community Treasure Hunt

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

Start Hunting!