Matlab按日期过滤记录

问题描述 投票:0回答:1

我是Matlab的小菜鸟,在做作业时遇到了麻烦

我有一个看起来像这样的Excel:

Date          column A         column B
1/1/2015     (double)         (double)
5/1/2015     (double)         (double)
6/1/2015     (double)         (double)
12/2/2015     (double)         (double)
13/2/2015     (double)         (double)
15/3/2015     (double)         (double)
11/4/2015     (double)         (double)
12/4/2015     (double)         (double)
13/4/2015     (double)         (double)
11/5/2015     (double)         (double)
13/5/2015     (double)         (double)
11/6/2015     (double)         (double)
11/7/2015     (double)         (double)
11/8/2015     (double)         (double)
11/9/2015     (double)         (double)
11/10/2015     (double)         (double)
11/11/2015     (double)         (double)
11/12/2015     (double)         (double)
.
########(string?) ...          ...
########(string?) ...          ...
15/8/2018         ...          ...
.
.
.

我将其导入并转换为表格,现在我需要对其进行过滤,仅保留每个季度的第一天。

由于Matlab与MySQL,java,我之前学过的东西以及我没有太多时间的东西有很大不同,所以我在这种绝望的情况下感到恐慌(这只是我的家庭作业的开始!),所以我真的需要一些帮助。

我不熟悉语法,这是我第一次问一个问题,对不起,如果我问一些愚蠢的问题。

matlab select filtering contains
1个回答
0
投票

您可以在Matlab中使用datetime类比较日期。

假设:1.您的日期格式为dd/MM/yyyy2.从Excel打印时,第1列中的日期已经排序3.标题为data.csv的csv文件的分隔符是一个空格,以下代码段应打印出每个季度的第一个出现日期的列。

clc; clear;

fid = fopen('data.csv');

% Retrieve data from file
data = textscan(fid, '%s %s %s', 'delimiter', ' ');

% Convert string to date objects 
% that enables date comparison
datesArray = datetime(data{1}, 'InputFormat', 'dd/MM/yyyy');

% Define start and end dates of each quarter
QstartDayMonth = ['01/01'; '01/04'; '01/07'; '01/10'];
QendDayMonth   = ['31/03'; '30/06'; '30/09'; '31/12'];

% Parse data to extract seasonal firsts
quart = 1;
for i = 1:length(datesArray)
  % Obtain year
  currentDate = datesArray(i);
  currentYear = num2str(currentDate.Year);

  % Define start date of current year's quarter
  quarterStart = strcat(QstartDayMonth(quart, :), '/', currentYear);
  quarterEnd   = strcat(QendDayMonth(quart, :)  , '/', currentYear);
  quarterStart = datetime(quarterStart, 'InputFormat', 'dd/MM/yyyy');
  quarterEnd   = datetime(quarterEnd, 'InputFormat', 'dd/MM/yyyy');

  % Check if current date lies in chosen quarter
  if (currentDate >= quarterStart)
    disp([data{1}{i}, '  ', data{2}{i}, '  ', data{3}{i}]);

    % If it does, advance the quarter to be checked
    quart = quart + 1;
    if (quart > 4)
      quart = 1;
    end
    continue;
  end
end
fclose(fid);
© www.soinside.com 2019 - 2024. All rights reserved.