How to use DATE Excel Function in Matlab vector calculations?

조회 수: 2 (최근 30일)
Edson Rojas
Edson Rojas 2021년 5월 2일
댓글: Steven Lord 2021년 5월 4일
Hi all. New around here. I have been using excel date function con get dates for a insurance policy. This is my formula and would like it to translate cleanly to matlab syntax.
Excel formula: =MIN(E;MAX(B;DATE(YEAR(T)-IF(MONTH(B)<MONTH(T)+1;0;1);MONTH(B);DAY(B))))
Where:
E: Expiring date.
B: Begining date.
T: Today
I would like to apply the code to a complete table. I´ve been thinking on doing it in separate columns, but I am sure there a more efficient approach...
Thanks!
Edson.

채택된 답변

Steven Lord
Steven Lord 2021년 5월 2일
Don't work with serial date numbers unless you absolutely have to. Use a datetime array instead.
dt = datetime('now') + hours(randi([-5, 5], 1, 3))
dt = 1×3 datetime array
02-May-2021 17:22:49 02-May-2021 20:22:49 02-May-2021 12:22:49
min(dt)
ans = datetime
02-May-2021 12:22:49
minutes(dt(3)-dt(1))
ans = -300
  댓글 수: 2
Edson Rojas
Edson Rojas 2021년 5월 4일
편집: Edson Rojas 2021년 5월 4일
Thanks Steven, just finished my function.. any advice on making it shorter/efficient? I tested it and works for vector calculations:
function x = mycalc(T,B,E)
%T = datenum('31122016','ddmmyyyy');
%B = datenum('01102016','ddmmyyyy');
%E = datenum('30102020','ddmmyyyy');
d = num2str(day(B),'%02d');
m = num2str(month(B),'%02d');
if month(B)<month(T)+1
i=0;
else
i=1;
end
y = num2str(year(T)-i);
fdmy = strcat(d,m,y);
nd = datenum(fdmy,'ddmmyyyy');
x = min(E,max(B,nd));
end
Steven Lord
Steven Lord 2021년 5월 4일
There's no need to use serial date numbers.
inputFormat = 'ddMMyyyy'; % For datetime mm is minute and MM is month
T = datetime('31122016', 'InputFormat', inputFormat)
T = datetime
31-Dec-2016
B = datetime('01102016', 'InputFormat', inputFormat)
B = datetime
01-Oct-2016
E = datetime('30102020', 'InputFormat', inputFormat)
E = datetime
30-Oct-2020
There are functions for extracting the parts of a datetime array:
[Y, M, D] = ymd(T)
Y = 2016
M = 12
D = 31
You can use those parts in reassembling a datetime. Or you could just perform date arithmetic using a datetime and either a duration or calendarDuration array.
Tplus1_version1 = datetime(Y, M+1, D)
Tplus1_version1 = datetime
31-Jan-2017
Tplus1_version2 = T + calmonths(1)
Tplus1_version2 = datetime
31-Jan-2017
You can do some other calculations.
[value, location] = min([T, B, E])
value = datetime
01-Oct-2016
location = 2
Since location was 2, the second element of the datetime vector [T, B, E] contains the minimum.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by