Search code examples
matlabmatrixtext-processingcell-arraytextscan

conversion of cell to matrix that contains text?


I have the text file that contains measurement data, the header is not that important so I used this to remove the first 25 lines

% Skip the first 25 lines
for i=1:25
fgetl(inputfile);
end

Then I used delimiter in order to get the data

   delimiter = '';
   values = textscan(inputfile, '%s', 'delimiter', delimiter);

I am trying to convert cell that consists of 1000 char as in the following. Here what I got

'2014_11_03_17-19-49 000 430114 516672 960.91 26.2'
'2014_11_03_17-19-49 001 430112 516656 960.91 26.2'
'2014_11_03_17-19-49 002 430112 516656 960.91 26.2'
'2014_11_03_17-19-49 003 430112 516656 960.91 26.2'

I am trying to convert cell that consists of 1000 char as in the previous I am concerning about (960.91 and 26.2) values only.

I tried to convert it to matrix but i got

this error Cannot support cell arrays containing cell arrays or objects.

Any idea how to just got those values into matrix to plot them.


Solution

  • Approach #1

    You can use the nifty importdata here -

    lines_skip = 25;
    values = importdata(inputfile,' ',lines_skip) %// using the delimiter ' ' here
    

    values would be a struct holding the data from inputfile.

    Thus, fourth column would be values.data(:,4), while values.data(:,5) would be the fifth one as shown here -

    >> values.data(:,4)
    ans =
      960.9100
      960.9100
      960.9100
      960.9100
    >> values.data(:,5)
    ans =
       26.2000
       26.2000
       26.2000
       26.2000
    

    Approach #2

    If you already have the cell array as listed in the question, you don't need to worry about reading the input file again. So, you have something like this -

    incell = {
        '2014_11_03_17-19-49 000 430114 516672 960.91 26.2'
        '2014_11_03_17-19-49 001 430112 516656 960.91 26.2'
        '2014_11_03_17-19-49 002 430112 516656 960.91 26.2'
        '2014_11_03_17-19-49 003 430112 516656 960.91 26.2'}
    

    Next, you can use cellfun with regexp to split each cell into columns using the delimiter ' ' -

    cellarr = cellfun(@(x) regexp(x,' ','Split'),incell,'un',0)
    values = vertcat(cellarr{:})
    

    which will get you -

    values = 
        '2014_11_03_17-19-49'    '000'    '430114'    '516672'    '960.91'    '26.2'
        '2014_11_03_17-19-49'    '001'    '430112'    '516656'    '960.91'    '26.2'
        '2014_11_03_17-19-49'    '002'    '430112'    '516656'    '960.91'    '26.2'
        '2014_11_03_17-19-49'    '003'    '430112'    '516656'    '960.91'    '26.2'
    

    That is, fifth and sixth columns from values would be the data you were looking to have after wrapping str2double around them : str2double(values(:,5)) and str2double(values(:,6)).