4

我需要将日期编号转换为其最接近的月末日期。我找到了一个在线链接,但对于大型矩阵来说效率很低(在http://www.mathworks.com/matlabcentral/fileexchange/26374-round-off-dates-and-times)。Matlab ( Financial Toolbox) 是否为此提供了内置函数?我找不到它。

date_in = 734421 ;
somefunction(date_in) --> Sept 2010

谢谢!

4

2 回答 2

6

基本上,听起来您在询问给定日期是否更接近上个月或下个月。如果您使用函数EOMDAY查找月末日期并使用 ADDTODATE将当前月份向上或向下移动 1,则可以大大简化所涉及的逻辑。这是一个将日期数字作为输入的示例函数:

function closestString = closest_month(dateNumber)

  dateVector = datevec(dateNumber);
  daysInMonth = eomday(dateVector(1),dateVector(2));
  if dateVector(3) > daysInMonth/2
    dateNumber = addtodate(dateNumber,1,'month');
  else
    dateNumber = addtodate(dateNumber,-1,'month');
  end
  closestString = datestr(dateNumber,'mmm yyyy');

end
于 2011-07-21T15:21:12.933 回答
1

我在以前的版本中有一些错误。这是合并到函数中的逻辑。它还会检查月份并进行相应更新。

function out = roundMonth(dateNumber)
    dateVector = datevec(dateNumber);
    day = dateVector(3);
    month = dateVector(2);
    year = dateVector(1);

    month = month + sign(day - 15 + double(~(month-2)))...
        + double(~(day-15 + double(~(month-2))));

    dateVector(1) = year + double((month-12)==1) - double((1-month)==1);
    dateVector(2) = mod(month,12) + 12*double(~mod(month,12));

    out = datestr(dateVector,'mmm yyyy');

例子:

1.

roundMonth(datenum('10-Oct-2010'))

ans =

Sep 2010

2.

roundMonth(datenum('20-Oct-2010'))

ans =

Nov 2010

3.

roundMonth(datenum('20-Dec-2010'))

ans =

Jan 2011

4.

roundMonth(datenum('10-Jan-2010'))

ans =

Dec 2009
于 2011-07-20T19:54:27.307 回答