Convert a heterogeneous cell array to a numeric array

I am using xlsread in MATLAB to read in sheets from an excel file. My goal is for each Excel column to be read as a numeric array. One of the columns has a combination of numbers and numbers + char. For example, the values ​​may be 200, 300A, 450, 500A, 200A, 100. Here is what I still have:

[num, txt, raw] = xlsread(fileIn, sheets{ii});    % Reading in each sheet from a for loop
myCol = raw(:, 4)                             % I want all rows of column 4
for kk=1:numel(myCol)
       if iscellstr(myCol(kk))
           myCol(kk) = (cellfun(@(x)strrep(x, 'A', ''), myCol(kk), 'UniformOutput', false));
       end
end

myCol = cell2mat(myCol);

This allows you to disconnect char from the number, but then I stay with

myCol =

[200]

'300'

[450]

'500'

'200'

[100]

which causes errors on cell2mat with:

cell2mat (myCol)

??? Error using ==> cell2mat at 46

All contents of an array of input cells must have the same data type.

It seems to me that I'm probably mixing () and {} somewhere. Can someone help me with this?

+5
2

[num, txt, raw] = xlsread('test.xlsx');
myCol = raw(:, 4);

idx = cellfun(@ischar,myCol ); %# find strings
data = zeros(size(myCol)); %# preallocate matrix for numeric data
data(~idx) = cell2mat(myCol(~idx)); %# convert numeric data
data(idx) = str2double(regexprep(myCol(idx),'\D','')); %# remove non-digits and convert to numeric
+7

myCol , , , - :

myCol = {200; '300A'; 450; '500A'; '200A'; 100};

, :

  • myCol, . , , CELLFUN, , :

    index = cellfun(@ischar,myCol);
    
  • . , 'A', , , ​​ STRREP :

    strrep(myCol(index),'A','')
    

    , , REGEXPREP, . :

    regexprep(myCol(index),'\D','')
    
  • . STR2DOUBLE:

    str2double(regexprep(myCol(index),'\D',''))
    

myCol. , :

>> index = cellfun(@ischar,myCol);
>> result(index,1) = str2double(regexprep(myCol(index),'\D',''));
>> result(~index) = [myCol{~index}]

result =

   200
   300
   450
   500
   200
   100
+2

All Articles