MATLAB Answers

0

Convert single string with many numbers to vector

Asked by Pati Stan on 31 Jul 2019
Latest activity Commented on by Stephen Cobeldick on 7 Aug 2019
I have the following string
hue = '10 20 30 40 50';
That I want to turn into a vector of those 5 values
hue_vec = [10 20 30 40 50];
How can I do this? Thanks in advance!

  0 Comments

Sign in to comment.

4 Answers

Answer by madhan ravi
on 31 Jul 2019
 Accepted Answer

hue_vec = str2double(regexp(hue,'\d+','match'))

  1 Comment

If you have decimals then the expressions would be:
hue_vec = str2double(regexp(hue,'\d*[\.]?\d*','match'))

Sign in to comment.


Answer by Fangjun Jiang
on 31 Jul 2019

a=str2num(hue);

  2 Comments

Also works great! Thanks!
Note that str2num relies on eval.

Sign in to comment.


Answer by Pati Stan on 31 Jul 2019

This worked beautifully! Thank you!

  0 Comments

Sign in to comment.


Answer by Stephen Cobeldick on 1 Aug 2019
Edited by Stephen Cobeldick on 1 Aug 2019

Very simple, very efficient, no evil eval:
>> hue = '10 20 30 40 50';
>> vec = sscanf(hue,'%f',[1,Inf])
vec =
10 20 30 40 50