How to plot date and time on x axis and data on y axis using matlab?

19 views (last 30 days)
Excel file is attatched and also code is given below,
Excel_data=xlsread('Excel_Worksheet.xlsx');
column_1= Excel_data(:,1);
column_2= Excel_data(:,2);
numex=numel(column_1);
Excel_data1='Excel_Worksheet.xlsx';
sheet = 1;
xlRange = 'D3';
for i=1:numex
finalresult(i)=column_1(i)+column_2(i);
xlswrite(Excel_data1,finalresult',sheet,xlRange)
end
[NUM TEXT RAW]=xlsread('Excel_Worksheet.xlsx');
H1=RAW(:,1);
H2=RAW(:,2);
plot(H1,H2);
On excecuting, it is showing an error like </matlabcentral/answers/uploaded_files/127407/Capture.JPG>

Answers (2)

jonas
jonas on 2 Aug 2018
Edited: jonas on 2 Aug 2018
The data import is all messy and you are trying to jam two cell arrays into the plot. Two options, either add the cell range of the data (excluding headers) after the xlsread.
[num,str]=xlsread('Excel_Worksheet.xlsx','A3:B100')
dates=datenum(str(:,1))
plot(dates,num)
datetick('x','HH:MM','keeplimits','keepticks')
Better yet, use readtable instead of xlsread. After the loop, replace your code by these lines
opts = detectImportOptions('Excel_Worksheet.xlsx','NumHeaderLines',2);
data=readtable('Excel_Worksheet.xlsx',opts,'ReadVariableNames',true);
plot(data{:,1},data{:,2});
  4 Comments
jonas
jonas on 21 Aug 2018
You're welcome. Feel free to accept the answer if it was helpful :)

Sign in to comment.


Peter Perkins
Peter Perkins on 3 Aug 2018
As Jonas suggests, if you are using a recent version of MATLAB, use readtable, and you should be able to just plot the resulting datetime values.
  6 Comments
amrutha raj
amrutha raj on 20 Aug 2018
Sir, just look at the excel sheet...the fifth cell time is 1:30:00..but in the readed str.mat it is 2:30:00 am..
jonas
jonas on 20 Aug 2018
Edited: jonas on 20 Aug 2018
Well, of course they are not synced row-wise. You start reading from A3, so the third row in the excel file will be the first row in the imported data variable..... The last rows are 100% the same, and the number of rows are also the same. So no value is missing. Case closed.
I will be replying in the other answer from now on, please do the same.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!