convert a string vector to a vector of numbers
Show older comments
Hello,
suppose I have a vector of string [1 2 3 4] and i want to change it to a vector of nmbers to do a numeric caculations, How can I do it? Thank's!
2 Comments
Walter Roberson
on 16 Apr 2013
Are the '[' and ']' in the string? Are the numbers only integers or possibly floating point ?
googo
on 16 Apr 2013
Answers (1)
Hi,
as long there are no [] in the string use textscan:
textscan('1 2 3 4 6.3','%f','delimiter',' ')
In the case there are use strrep to remove the [ or ] before calling textscan.
8 Comments
googo
on 16 Apr 2013
The problem here is you dont have a delimiter. So you cant use simply textscan ( i was wrong) and also not str2num because str2num(string) would give 1234 and not [1 2 3 4]. But this should work assuming your values have one letter only:
string=['1' '2' '3' '4']
double_vec = cell2mat(textscan(sprintf('%c ',string),'%f','delimiter',' '))
Where does your string come from? Maybe its better to create the double values before your put all your characters together into one string. In that case you can use str2num.
You can use str2num(freq) in your case because freq is a column vector. It wouldnt work if freq is a row vector.
To see what differnce it makes if freq is column or row vector take a look at:
%row vector will give number 12
>> str2num(['1','2'])
ans =
12
%column vector will give [1; 2] as double values
>> str2num(['1';'2'])
ans =
1
2
In your post the string was a row vector, thats why I thought it gets a bit more complicated.
Walter Roberson
on 16 Apr 2013
That code cannot handle more than 9 occurrences of the ngram.
Walter Roberson
on 16 Apr 2013
You have
t(i,n+1)=num2str(c);
the destination t(i,n+1) is a single character. The number 10 and upwards require two (or more) characters to represent as a string. Therefore if c reached 10 (occurrences) the code would fail. This suggests that you have a code design problem.
googo
on 16 Apr 2013
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!