Search code examples
matlabplotfopentextscan

How to import a csv file with date in matlab and plot it?


I have a csv file that has two columns, date and float, the date format is weird though (Jan 1 2016 9:55:00 PM), how can I import it to matlab and draw it as a plot? this is what i tried:

fid = fopen('all.csv');
if fid>0    
     data = textscan(fid,'%s %d','Delimiter',',');
     % close the file
     fclose(fid);         
end
x = data(:,1);
y = data(:,2);

plot(x,y);

but i get an error not enough arguments

Sample of all.csv:

Jan 1 2016 9:55:00 PM, 12493829,
Jan 2 2016 7:55:00 AM, 83747283,
Jan 3 2016 2:55:00 PM, 89572948,
Jan 4 2016 8:55:00 AM, 95862744,

the error:

Error using plot
Not enough input arguments.

Error in test (line 10)
plot(x,y);

Solution

  • The error appears since you're inputting cell arrays in the plot function.

    x = data{:,1};   %You need { } here, not ()
    y = data{:,2};
    
    plot(1:numel(x), y, 'o-');
    %Ensuring the xticks are as required and changing the xticklabels to datetime values and 
    %rotating the labels for better visualisation ('xticklabelrotation' requires >= R2014b)
    set(gca,'xtick',1:numel(x),'xticklabel',x,'xticklabelrotation',45);  
    

    Output:

    output