我有一个有趣的问题,涉及从矩阵中取出最后一天并找到其上个月的一天。例如,如果今天的日期是 Oct-10-2011,您尝试搜索 Sep-10-2011 或第一天 < 2011 年 9 月 10 日在矩阵中。
Matrix有多个ID,最后交易日期可能不相同。
需要矢量化解决方案。谢谢!
mat = [
1000 734507 11 ; 1000 734508 12 ; 1000 734509 13 ;
2001 734507 21 ; 2001 734508 22 ; 2001 734513 23 ; 2001 734516 25 ;
1000 734536 14 ; 1000 734537 15 ; 1000 734538 16 ;
2001 734536 26 ; 2001 734537 27 ; 2001 734544 28 ; 2001 734545 29;2001 734546 30
];
% datestr(mat(:,2))
[~,m,~] = unique(mat(:,1), 'rows', 'last') ;
lastDay = mat(m,;) ;
尝试使用 addtodate
在这里获取上个月日期,但失败(超过 1 行)
一旦获得每个 ID 的最后日期,我就需要获取精确的_day_lastmonth。之后,我需要获取这一天或最接近这一天的数据(应该是)。
回答:
current_lastdays = [1000 734538 16 ; 2001 734546 30] ; % 4-Feb-2011, 12-Feb-2011
matching_lastmon = [1000 734507 11 ; 2001 734513 23] ; % 4-Jan-2011, 10-Jan-2011
I have an interesting problem that involves taking the last day
from a matrix and finding its last month
day. Eg, if the date today is Oct-10-2011, you try to search for Sep-10-2011 or the first day < Sep-10-2011 in the matrix.
Matrix has multiple IDs and last trading dates may not be the same.
Vectorized solution is desired. Thanks!
mat = [
1000 734507 11 ; 1000 734508 12 ; 1000 734509 13 ;
2001 734507 21 ; 2001 734508 22 ; 2001 734513 23 ; 2001 734516 25 ;
1000 734536 14 ; 1000 734537 15 ; 1000 734538 16 ;
2001 734536 26 ; 2001 734537 27 ; 2001 734544 28 ; 2001 734545 29;2001 734546 30
];
% datestr(mat(:,2))
[~,m,~] = unique(mat(:,1), 'rows', 'last') ;
lastDay = mat(m,;) ;
Tried using addtodate
to get last-month-date here but it fails (more than 1 row)
Once I get the last-dates for each ID, I need to get the exact_day_lastmonth. After this, I need to get data on this day OR the day nearest to it (should be < exact_day_lastmonth
).
Answer:
current_lastdays = [1000 734538 16 ; 2001 734546 30] ; % 4-Feb-2011, 12-Feb-2011
matching_lastmon = [1000 734507 11 ; 2001 734513 23] ; % 4-Jan-2011, 10-Jan-2011
发布评论
评论(1)
除非您想冒具有复杂索引的相当大的数组的风险,否则我认为循环是可行的方法。
Unless you want to risk rather large arrays with complicated indexing, I think a loop is the way to go.