Reading text data from a CSV file in MATLAB

前端 未结 5 1302
-上瘾入骨i
-上瘾入骨i 2020-12-21 14:37

my data is in following form:

days of week      date        time(hrs)        visitors
mon            jan 2 2010     900               501 
mon            jan         


        
相关标签:
5条回答
  • 2020-12-21 14:54

    Here is how I would read the tab-separated values, and parse the dates:

    %# read and parse file
    fid = fopen('data.csv','rt');
    C = textscan(fid, '%s %s %s %d', 'Delimiter','\t', 'HeaderLines',1, ...
        'MultipleDelimsAsOne',true, 'CollectOutput',false);
    fclose(fid);
    
    %# get date and number of visitors
    dt = datenum(strcat(C{2}, {' '}, C{3}), 'mmm dd yyyy HHMM');
    visitors = C{4};
    
    %# plot
    plot(dt,visitors)
    datetick('x')
    xlabel('time of day'), ylabel('visitors')
    

    enter image description here

    As for the day-of-week column, you can get it as:

    >> C{1}                        %# first column from file
    ans = 
        'mon'
        'mon'
        'mon'
    
    >> cellstr(datestr(dt,'ffffd'))  %# actual day of week from parsed dates
    ans = 
        'Sat'
        'Sat'
        'Sat'
    

    this produces different days (either your data posted was simply made-up, or you have a bug in the part that generated those dates!)

    0 讨论(0)
  • 2020-12-21 15:05

    You could download my csvimport submission from the File Exchange. Assuming your data is tab separated, you can read it using:

    [days datecol timecol visitors] = csvimport( 'file.txt', 'delimiter', '\t', ...
           'columns', {'days of week', 'date', 'time(hrs)', 'visitors'} );
    

    The first 2 output parameters will cell arrays of strings while the last 2 will be double matrices.

    0 讨论(0)
  • 2020-12-21 15:12

    Taking prompts from this previous question,

    fid = fopen('filename.txt');
    % Skip a line for the header
    s = fgetl(fid);
    % Read the rest into data
    data = textscan(fid, '%s %s %d %d %d %d');
    % Close the file
    fclose(fid);
    

    The days of the week are in the first cell of data.

    0 讨论(0)
  • 2020-12-21 15:14

    You could try to use dlmread. It can take any ASCII delimiter. I think it might suit your requirements. See here.

    0 讨论(0)
  • 2020-12-21 15:15

    If you are just getting started with (a recent version of) matlab, the easiest way is to use the 'import wizard'.

    A few simple steps:

    1. Browse to your file and right click it
    2. Choose the option to import
    3. Select the choice to store things as cell array (Vectors or matrices wont work).
    4. Click Import

    Optionally you can click next to import and select that you want to generate the code for this procedure. However, this will likely be a bit verbose. If you just need to do it once, I would recommend this method.

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