matlabtextscan

how to use textscan in matlab


i'm trying to inesrt the following text file into a matrix in matlab

time.txt

I tried to use 'textscan'

fileID = fopen('Uz10.txt');

Uz10=textscan(fileID,'%d');

fclose(fileID);

but alwayes got,

Undefined operator '*' for input arguments of type 'cell'.

can anybody gives me the right format?


Solution

  • You can modify you code this way:

    1) by specifying %s as the format: in this case, textscan returns a cellarray of string

    fileID = fopen('Uz10.txt');
    % Uz10=textscan(fileID,'%d:%d');
    Uz10=textscan(fileID,'%s');
    fclose(fileID);
    

    Output:

    >> Uz10{1}
    
    ans = 
    
        '0:00'
        '0:10'
        '0:20'
        '0:30'
         ...
    

    2) by specifying %d:%d as the format: in this case, textscan returns a (1x2) cellarray of int32 type containing the two digit of each row. Then you can concatenate them in order have a (nx2) matrix

    fileID = fopen('Uz10.txt');
    Uz10=textscan(fileID,'%d:%d');
    % Uz10=textscan(fileID,'%s');
    fclose(fileID);
    
    t=[Uz10{1} Uz10{2}]
    

    Output:

    >> t=[Uz10{1} Uz10{2}]
    
    t =
    
               0           0
               0          10
               0          20
               0          30
               ...        ...
    

    If you want to manage the data as time data you can use the function datetime.

    For example (using the first of the above format to read the input file):

    datetime(Uz10{1},'InputFormat','m:ss')
    

    Output:

    >> datetime(Uz10{1},'InputFormat','m:ss')
    
    ans = 
    
       24-Sep-2017 00:00:00
       24-Sep-2017 00:00:10
       24-Sep-2017 00:00:20
       24-Sep-2017 00:00:30
       ...