簡體   English   中英

Matlab中的If-Else時間陳述

[英]If-Else Statement of Time in Matlab

嗨,我成功地編寫了這樣的代碼,其中輸入了我的計算機時間和日期,如下所示

    function [Y, M, D, H, MN, S] = fcn()
    coder.extrinsic('now');
    coder.extrinsic('datevec');
    Y = 0;
    M = 0;
    D = 0;
    H = 0;
    MN = 0;
    S = 0;
   [Y, M, D, H, MN, S] = datevec(now);
   end

它工作得很好。 然后,我嘗試為該控制器制作另一個塊,如果在這段時間內不在輸出,則在7 AM-5PM之間輸出1,如果不在這段時間內輸出0,則我的代碼如下所示

   function y = fcn(u)

   u = datestr(7:00AM:5:00PM)
  if u = datestr(7:00AM:5:00PM)
  y=1;
  else
   y=0;

  end

但是發生了錯誤。 請幫助我找出問題所在。 謝謝

首先,您已經完成的第一個功能已經在MATLAB中內置為clock

關於您的問題,有很多解決問題的方法,但是我認為最簡單的方法是從一天開始算起秒數。

使用clock命令,您將以[year month day hour minute second]格式獲取當前時間的向量。 因此,從一天開始經過的時間為3600*time(4) + 60*time(5) + time(6) ,即3600次小時加60次分鍾加秒。 從00:00:00到7:00:00 7 * 3600秒過去了。 同樣,從00:00:00到17:00:00 17 * 3600秒過去了。 因此,您可以只比較這些值來確定它是否介於7AM和5PM之間:

function y = IsBetween5AMand7PM
    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;

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM