matlabtexttextscan

read text delimited file and write to excel in matlab


I have a txt file in this format:
Right,28772.163,39356.163,1,Speaker1 sp,39356.163,49499.163,99,Speaker1 sp,129129.21,147210.21,99,Speaker2 Next step is,147210.21,160881.21,1,Speaker2 surgery's,160881.21,181608.21,1,Speaker2

and it goes on (it has 1016 rows). I would like to convert it into excel file. I tried the following

fileID = fopen('test_datum.txt');
C = textscan(fileID,'%s %f32 %f32 %d8 %s');

But it inserts the data into a 1016X5 cell. I would like later to write this cell into an excel file.
thank you


Solution

  • The textscan function can sometimes be tricky to deal with. The data format is hard to define and it tends to cram data into a cell vector (reordering the result into a single cell matrix is kinda annoying). What I suggest you is to use the readtable function instead:

    T = readtable('data.txt')
    
    
         Var1           Var2         Var3       Var4       Var5   
    ______________    _________    _________    ____    __________
    
    'Right'           28772.163    39356.163     1      'Speaker1'
    'sp'              39356.163    49499.163    99      'Speaker1'
    'sp'              129129.21    147210.21    99      'Speaker2'
    'Next step is'    147210.21    160881.21     1      'Speaker2'
    'surgery's'       160881.21    181608.21     1      'Speaker2'
    

    If you have a Matlab release greater than or equal to R2016b, you can previously run the detectImportOptions function on the file. The result of the scan can be tweaked according to your needs (you can change the variable names, variable types, default for missing values, etc...):

    opts = detectImportOptions('data.txt');
    
    % the previous values where char, double, double, double, char
    opts.VariableTypes = {'char' 'single' 'single' 'int8' 'char'};
    % alternatively, this can be used:
    % opts = setvartype(opts,{'char' 'single' 'single' 'int8' 'char'})
    
    T = readtable('data.txt',opts)
    
    
         Var1           Var2        Var3      Var4       Var5   
    ______________    ________    ________    ____    __________
    
    'Right'           28772.16    39356.16     1      'Speaker1'
    'sp'              39356.16    49499.16    99      'Speaker1'
    'sp'              129129.2    147210.2    99      'Speaker2'
    'Next step is'    147210.2    160881.2     1      'Speaker2'
    'surgery's'       160881.2    181608.2     1      'Speaker2'
    

    On the top of that, tables are really easy to export to Excel files. All you have to do is to use the writetable function with the appropriate settings.