3

how to convert a string to an array of numbers? in example : str='1,2,3,4.5' to number=[1 2 3 4.5].

I wrote the code below, but it has a problem.

str='1,2,3,4.5';
tmp = regexp (str,',','split');
tmp2=[];
for(i=1:length(tmp))
tmp2(i)=cell2mat(tmp(i))
end
1
  • Future readers should check the answers to: stackoverflow.com/questions/14895220/… for very concise methods of converting strings to array of numbers. Commented Feb 15, 2013 at 13:25

3 Answers 3

4

Technically, @ame.b's answer is the correct one. But for the sake of diversity, you can also do the following in this case, because the separators are ,:

str2num(str)
Sign up to request clarification or add additional context in comments.

2 Comments

Even better, I say! I just did not think of this one as I rarely use it myself.
str2double is safer, especially since str2num is based on eval. I wouldn't recommend using str2num.
3

str2double is what you need where you used cell2mat.

edit: You can even replace the final four lines (i.e. the for loop and the initialisation of tmp2) by a call to cellfun:

tmp2=cellfun(@str2double,tmp)

1 Comment

@ame.b: You don't need cellfun to run str2double on cell array of strings. Just str2double(tmp) should work.
3

I must be missing something here, but why can't you just use sscanf? For example:

sscanf('1,2,3,4.5','%f,')

ans =

 1.0000
 2.0000
 3.0000
 4.5000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.