How to use DATE Excel Function in Matlab vector calculations?

2 views (last 30 days)
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.

Accepted Answer

Steven Lord
Steven Lord on 2 May 2021
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 Comments
Edson Rojas
Edson Rojas on 4 May 2021
Edited: Edson Rojas on 4 May 2021
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 on 4 May 2021
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.

Sign in to comment.

More Answers (0)

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!