Convert a cell column of strings to doubles
    4 views (last 30 days)
  
       Show older comments
    
I have a cell column of strings which looks like the attached file. How can I convert the column to double-precision values?
1 Comment
  Stephen23
      
      
 on 15 Jul 2015
				Please try attaching your data again. Press then parperclip button, then both the Choose file and Attach file buttons.
Accepted Answer
  Star Strider
      
      
 on 15 Jul 2015
        See if this does what you want:
D = load('string_column.mat');
data = D.owner;
out = cellfun(@(x) str2num(char(x)), data);
2 Comments
More Answers (2)
  Stephen23
      
      
 on 15 Jul 2015
        
      Edited: Stephen23
      
      
 on 15 Jul 2015
  
      >> A = {'1.2';'2.3';45.6789';'Inf'};
>> B = str2double(A);
B =
    1.2000
    2.3000
   45.6789
  Inf
3 Comments
  Stephen23
      
      
 on 15 Jul 2015
				
      Edited: Stephen23
      
      
 on 15 Jul 2015
  
			The problem is that data is not a cell array of strings, as you think it is, but actually mostly it is a cell array of cells containing strings, except for the last four cells (which are strings):
>> iscellstr(owner)
ans =
     0
>> owner(1:5)
ans = 
    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
>> owner(end-6:end)
ans = 
    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
    '0'       
    '0'       
    '0'       
    '0'
You can solve this as follows:
>> idx = cellfun('isclass',owner,'cell');
>> owner(idx) = [owner{idx}];
>> out = str2double(owner);
>> out(1:5)
ans =
     1
     2
     3
     4
     5
>> out(end-6:end)
ans =
        2300
        2301
        2302
           0
           0
           0
           0
This is the data file that I used:
  Guillaume
      
      
 on 15 Jul 2015
         str2double(vertcat(owner{:}))
works, because your each cell of your cell array (except for the last four) is actually itself a cell array which in turn contain the string.
The vertcat above convert your cell array of single cell arrays of strings into a cell array of strings.
0 Comments
See Also
Categories
				Find more on Characters and Strings 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!

