- 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.
Find the index of same date from two datetime vector
7 次查看(过去 30 天)
显示 更早的评论
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/594650/image.jpeg)
0 个评论
回答(1 个)
Rupesh
2024-2-26
编辑:Rupesh
2024-2-26
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.
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!
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!