Find the index of same date from two datetime vector

10 views (last 30 days)
Hi. I have two vectors datetime and i need to find the index of vector Gsm where the date is the same of the days i extract in the previous loop. I try with the loop y and it works until i find a day that isn't in the vector Gsm.When it happens, the loop give me the error that i have a 1x1 on left side and 0x1 on the right. I try with the if condition to assign NaN to that value, but it doesn't work. There is a function to find the index of same value from two vector or how can i change the script to skip to the next date when the second vector don't have that date. Thank you very much

Answers (1)

Rupesh
Rupesh on 26 Feb 2024
Edited: Rupesh on 26 Feb 2024
Hi Giacomo Abrardo,
I understand that you are trying to match dates between two vectors and extract corresponding values from another array, but you encounter an error when a date in "Giorno_sel" is not present in "Gsm", which disrupts the loop. To handle these non-matching dates, without causing an error in the loop, the solution should either assign "NaN" to these non-matching dates or skip them entirely, allowing the loop to continue processing the remaining dates. This approach ensures that the loop completes successfully, regardless of whether all dates in "Giorno_sel" find a match in "Gsm".However, your current script seems to have several syntax errors. Below is modified version of the given script.
for j = 1:Q
INDAP = find(TT1{:,K} >= Yd(j,k) & TT1{:,K} <= Yd(j+1,k));
Giorno_sel = Giorni(INDAP);
N9 = length(Giorno_sel);
XX = NaN(N9,1); % Preallocate XX with NaNs
for y = 1:N9
Top = Giorno_sel(y);
LOL = find(Gsm == Top);
if isempty(LOL)
XX(y,1) = NaN; % Already NaN by preallocation, but kept for clarity
else
XX(y,1) = SM(LOL,K);
end
end
end
The following changes need to be done to the script so that it can work as expected.
  • Fixed the syntax for accessing elements in “Giorno_sel” by using parentheses instead of the bitwise OR operator.
  • Used “isempty” to check if LOL is empty.
  • Reallocated the XX array with NaN values before the inner loop. This way, if LOL is empty, XX(y,1) is already NaN, and you don't need to explicitly set it again.
With these corrections, your script should iterate over the dates correctly and assign NaN to XX(y,1) when there is no matching date in Gsm. When a matching date is found, it will assign the corresponding value from SM(LOL,K) to XX(y,1).
You can also refer to the below documents regarding operations of all build-in functions involved in the above script and some examples related to vectorization used in the above script.
Hope this helps!

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!