I have 2 columns in a matrix. 1st column has the dates. 2nd column has the values. How do I grab all values from 2nd column associated with its date from the 1st column??

3 Ansichten (letzte 30 Tage)
I have a much larger data set, but this is just a smaller sample size example of what I would like to do.
I want to grab all values from 4/1/18: 6
I want to grab all values from 4/2/18: 22, 4
I want to grab all values from 4/2/18: 2, 12, 8
Matrix Example:
Column 1 Column 2
4/1/18 6
4/2/18 22
4/2/18 4
4/3/18 2
4/3/18 12
4/3/18 8

Antworten (3)

Dyuman Joshi
Dyuman Joshi am 16 Apr. 2022
%example, not sure which date format and data type you are using
y={datetime('2018-01-04') 6;datetime('2018-02-04') 22;datetime('2018-02-04') 4;datetime('2018-03-04') 2;datetime('2018-03-04') 12;datetime('2018-03-04') 8}
y = 6×2 cell array
{[04-Jan-2018]} {[ 6]} {[04-Feb-2018]} {[22]} {[04-Feb-2018]} {[ 4]} {[04-Mar-2018]} {[ 2]} {[04-Mar-2018]} {[12]} {[04-Mar-2018]} {[ 8]}
z=unique(cellfun(@(x) x, y(:,1)))
z = 3×1 datetime array
04-Jan-2018 04-Feb-2018 04-Mar-2018
for i=1:numel(z)
y(find(cellfun(@(x) x, y(:,1))==z(i)),2)'
%you can use curly parenthesis as well
end
ans = 1×1 cell array
{[6]}
ans = 1×2 cell array
{[22]} {[4]}
ans = 1×3 cell array
{[2]} {[12]} {[8]}

Scott MacKenzie
Scott MacKenzie am 16 Apr. 2022
Something like this will work:
% test data
d = { '4/1/18', 6;
'4/2/18', 22;
'4/2/18', 4;
'4/3/18', 2;
'4/3/18', 12;
'4/3/18', 8 };
dt = datetime(d(:,1), 'InputFormat','MM/dd/yy');
value = cell2mat(d(:,2));
query1 = dt == datetime('4/1/18', 'InputFormat','MM/dd/yy');
v1 = value(query1)
v1 = 6
query2 = dt == datetime('4/2/18', 'InputFormat','MM/dd/yy');
v2 = value(query2)
v2 = 2×1
22 4
query3 = dt == datetime('4/3/18', 'InputFormat','MM/dd/yy');
v3 = value(query3)
v3 = 3×1
2 12 8

Campion Loong
Campion Loong am 18 Mai 2022
This kind of tasks is what timetable is built for:
% Using your small example
tt = timetable(datetime(2018,4,[1;2;2;3;3;3]), [6;22;4;2;12;8])
tt = 6×1 timetable
Time Var1 ___________ ____ 01-Apr-2018 6 02-Apr-2018 22 02-Apr-2018 4 03-Apr-2018 2 03-Apr-2018 12 03-Apr-2018 8
% Simply subscript to the data at the timestamp you are looking for,
% e.g. 4/2/2018
tt(datetime(2018,4,2),:)
ans = 2×1 timetable
Time Var1 ___________ ____ 02-Apr-2018 22 02-Apr-2018 4
Bonus: use timerange if you want to get at all data within a range of time
% Between 4/2/2018 and 4/3/2018 (closed interval)
tt(timerange(datetime(2018,4,2), datetime(2018,4,3), 'closed'), :)
ans = 5×1 timetable
Time Var1 ___________ ____ 02-Apr-2018 22 02-Apr-2018 4 03-Apr-2018 2 03-Apr-2018 12 03-Apr-2018 8

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by