Creating a for loop to see if date exists
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Devarshi Patel
am 11 Jun. 2019
Beantwortet: Peter Perkins
am 12 Jun. 2019
I have two array with date, first array have multiple dates in 5x3 cell such as each cell have year, month, and date in it:
firstarray=[2019 5 03;
2019 4 03;
2019 4 05;
2019 4 06;
2019 3 05]
Another array is 1x3 which has the date I am looking for.
[2019 4 05]
How can I create a for loop to find that date and find the position of where it is located?
0 Kommentare
Akzeptierte Antwort
Rik
am 11 Jun. 2019
If you insist or keeping it as a double, you can use ismember three times, but it makes more sense to make use of the datetime class.
first=[2019 5 03;
2019 4 03;
2019 4 05;
2019 4 06;
2019 3 05];
test=[2019 4 05];
first=datetime(first(:,1),first(:,2),first(:,3));
test=datetime(test(:,1),test(:,2),test(:,3));
pos=find(ismember(first,test));
date=first(pos);
3 Kommentare
Steven Lord
am 11 Jun. 2019
If you need to keep first and test as double arrays, don't call ismember three times. Call it once with the 'rows' option.
first=[2019 5 03;
2019 4 03;
2019 4 05;
2019 4 06;
2019 3 05];
test=[2019 4 05; 2019 4 04];
[isPresent, wherePresent] = ismember(test, first, 'rows')
matched = [test(isPresent, :), first(wherePresent(isPresent), :)]
unmatched = test(~isPresent, :)
Weitere Antworten (1)
Peter Perkins
am 12 Jun. 2019
Also, it may be that you need to "find that date and find the position of where it is located" because you'll then use that location to index into somethign else. If that's truem sacve yourself a lot of hassle, and create a timetable. For example:
>> t = timetable([1;2;3;4;5],'RowTimes',datetime(2019,6,[1 2 3 5 9]))
t =
5×1 timetable
Time Var1
___________ ____
01-Jun-2019 1
02-Jun-2019 2
03-Jun-2019 3
05-Jun-2019 4
09-Jun-2019 5
>> t.Var1('5-Jun-2019')
ans =
4
0 Kommentare
Siehe auch
Kategorien
Mehr zu Dates and Time finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!