Reading date and time from CSV file in MATLAB

后端 未结 2 900
星月不相逢
星月不相逢 2020-12-01 10:13
datetime, M01, M02, M03, M04, M05, M06
8/15/2009 0:00, 5.8, 7.8, 7.8, 7.3, 0, 7.9
8/15/2009 0:10, 7.1, 8.1, 8.1, 7.7, 0, 8.1
8/15/2009 0:20, 6.8, 7.4, 7.6, 7.1, 0, 7         


        
相关标签:
2条回答
  • 2020-12-01 10:36

    According to your comment above, if the data looks like:

    datetime, M01, M02, M03, M04, M05, M06
    8/15/2009 0:00, 5.8, 7.8, 7.8, 7.3, 0, 7.9
    8/15/2009 0:10, 7.1, 8.1, 8.1, 7.7, 0, 8.1
    8/15/2009 0:20, 6.8, 7.4, 7.6, 7.1, 0, 7.3
    8/15/2009 0:30, 5.6, 6.8, 7.1, 6.6, 0, 6.8
    8/15/2009 0:40, 3.9, 6.2, 6.4, 6.2, 0, 6.4
    8/15/2009 0:50, 4.6, 5.5, 6.1, 5.8, 0, 5.6
    8/15/2009 1:40, 7, 7 7.2, 6.9, 0, 6.3
    

    then use the following to read it as a matrix:

    fid = fopen('file.csv', 'rt');
    a = textscan(fid, '%s %f %f %f %f %f %f', ...
          'Delimiter',',', 'CollectOutput',1, 'HeaderLines',1);
    fclose(fid);
    
    format short g
    M = [datenum(a{1}) a{2}]
    

    ... and the output I get:

    M =
        7.34e+005        5.8        7.8        7.8        7.3          0        7.9
        7.34e+005        7.1        8.1        8.1        7.7          0        8.1
        7.34e+005        6.8        7.4        7.6        7.1          0        7.3
        7.34e+005        5.6        6.8        7.1        6.6          0        6.8
        7.34e+005        3.9        6.2        6.4        6.2          0        6.4
        7.34e+005        4.6        5.5        6.1        5.8          0        5.6
        7.34e+005          7          7        7.2        6.9          0        6.3
    

    if you set the display format to a long output, you will see the full numbers (note they are still stored in full), or use fprintf:

    fprintf('%.9f\n', M(:,1))
    
    734000.000000000
    734000.006944445
    734000.013888889
    734000.020833333
    734000.027777778
    734000.034722222
    734000.069444445
    
    0 讨论(0)
  • 2020-12-01 10:43

    TEXTSCAN by itself won't convert the date, but you can call DATENUM on just the column that needs it.

    f = fopen('datafile.txt');
    data = textscan(f, '%s %f %f %f %f %f %f', 'Delimiter', ',', 'HeaderLines', 1);
    fclose(f);
    data{1} = datenum(data{1});
    

    will return a cell array data of doubles where the first column is the MATLAB datenum corresponding to each date, and each other column is the corresponding column from the file.

    0 讨论(0)
提交回复
热议问题