Creating a for loop to see if date exists
조회 수: 2 (최근 30일)
이전 댓글 표시
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
채택된 답변
Rik
2019년 6월 11일
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
Steven Lord
2019년 6월 11일
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, :)
추가 답변 (1개)
Peter Perkins
2019년 6월 12일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!