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?

采纳的回答

Rik
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
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
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by