工作日和周末的 Matlab 代码

Matlab Code for weekdays and weekends

我能够成功地制定一个时间表,如果时间在早上 7 点到下午 5 点之间,则输出为 1,否则为 0,时间基于我的计算机。然而,周一至周日也是基于我的计算机。我找不到在周一至周六输出 1 并在周日输出 0 的解决方案。我的代码如下

function y = IsBetween5AMand7PM
coder.extrinsic('clock');
time = zeros(1,6);
time = clock;
current = 3600*time(4) + 60*time(5) + time(6); %seconds passed from the beginning of day until now
morning = 3600*7; %seconds passed from the beginning of day until 7AM
evening = 3600*17; %seconds passed from the beginning of day until 5PM
y = current > morning && current < evening;

end

现在这里的时间已经正确了,我需要的是当天(周一至周日)获得我需要的输出。此 matlab 代码也在 Simulink 块上的 matlab 函数内。

如果您像这样使用工作日,您可以生成一个 0/​​1 值,正如您为今天的日期指定的那样:

if (weekday(now) > 1)
   day_of_week_flag = 1;
else
   day_of_week_flag = 0;

或者,如果您愿意,这个单行代码可以做同样的事情,但如果您不熟悉语法,则可能不会那么容易阅读:

day_of_week_flag = ( weekday(now) > 1);

您也可以使用这样的日期字符串来转换其他日期:

day_of_week_flag = ( weekday('01-Mar-2016') > 1 )

最后,如果您有一个 date/time 值的数值数组,例如 [2016 3 3 12 0 0],您首先需要使用 datenum 转换为序列日期,然后使用工作日:

time = clock;
day_of_week_flag = ( weekday(datenum(time)) > 1);

另一种不使用工作日的检查方法如下:

time = clock;
day_of_week = datestr(time, 8);
if (day_of_week == 'Sun')
   day_of_week_flag = 0;
else
   day_of_week_flag = 1;