Creating a for loop to see if date exists

3 visualizaciones (últimos 30 días)
Devarshi Patel
Devarshi Patel el 11 de Jun. de 2019
Respondida: Peter Perkins el 12 de Jun. de 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?

Respuesta aceptada

Rik
Rik el 11 de Jun. de 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 comentarios
Steven Lord
Steven Lord el 11 de Jun. de 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, :)
Devarshi Patel
Devarshi Patel el 12 de Jun. de 2019
Thank you! Your code worked as well!

Iniciar sesión para comentar.

Más respuestas (1)

Peter Perkins
Peter Perkins el 12 de Jun. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by