how to get unique value of datetime and sum all of the value ?
35 views (last 30 days)
Show older comments
Muhannad AL-hazmi
on 31 May 2021
Commented: Muhannad AL-hazmi
on 1 Jun 2021
Hello Matlab Community
so i'm really new in Datetime class , so what i want is to sum all the value in the column 5 which is unit sold with it corrosponding dates but the dates are scatter and repeated so i want sum all of the unit with the same date , so how to do it?, here what i wrote and my brian just stop working i guess
date = FinancialSample{:,13};
U_sold = FinancialSample{:,5};
%plot(date,U_sold,'o')
[unqdate,idx,idx1] = unique(date);
for c = FinancialSample.Date == unqdate(:)
sum1(c)=sum(U_sold(c))
end
here the datetime array from microsoft https://docs.microsoft.com/en-us/power-bi/create-reports/sample-financial-download
edit: is there something not clear in my question plz ask me .
0 Comments
Accepted Answer
Jakob B. Nielsen
on 1 Jun 2021
Hi Muhannad,
You have made a good start, you have a list of all unique dates in your unqdate. One thing I would recommend is to convert your date strings into serial date numbers, because it makes it much easier (in my opinion, anyway) to use logical indexing later on. You do this by saying
date_nums=datenum(date,'dd/mm/yyyy');
unqdate=unique(date_nums);
After this, you want to have a loop that executes the number of times corresponding to the size of your unqdate variable:
for i=1:size(unqdate,1)
Now you can use logical indexing to solve your problem. Its a little twisty but bear with me: you want to take from U_sold those indexes for which it is true that your full date vector matches the i'th entry in the unique date vector. And then sum the values from those indexes.
sales(i)=sum(U_sold(date_nums==unqdate(i)));
realdate{i}=datestr(unqdate(i),'dd/mm/yyyy') %and convert your unique date number back to a date string again
end
Logical indexing is a bit hairy when you first look at it, but think of it this way; you formulate a true/false statement, and only select the indexes for which the statement is true. An illustrative example:
A=[1 2 3 4 5 1 1];
%first, look at
A==1
%gives this: 1 0 0 0 0 1 1
%Which means if you ask for
A(A==1)
%you get simply 1 1 1 because it only takes the values out, for which we
%got a logical 1 before.
%We are essentially doing the same thing in your problem, but for unique dates
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!