在Matlab单元格数组中使用find来查找每个日期

时间:2018-02-06 12:05:53

标签: matlab datetime find

我有以下单元格数组(实际上更宽更长):

Table = cell(5,4);

Table{1,1} = 'Datetime';
Table(2,1) = num2cell(datetime('01.01.1999','InputFormat','dd.MM.yyyy'));
Table(3,1) = num2cell(datetime('01.01.1999','InputFormat','dd.MM.yyyy'));
Table(4,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));
Table(5,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));

Table{1,2} = 'ZeroAndOne';
Table{2,2} = 1;
Table{3,2} = 1;
Table{4,2} = 0;
Table{5,2} = 1;

我想添加两列,一个列为1,当'ZeroAndOne'第一次为1时,为每个日期;当“ZeroAndOne”最后一次为每个日期时,一列为1。 你会如何一般地做到这一点?这是“手工”的解决方案:

Table{1,3} = 'OneForFirstTime';
Table{2,3} = 1;
Table{3,3} = 0;
Table{4,3} = 0;
Table{5,3} = 1;

Table{1,4} = 'OneForLastTime';
Table{2,4} = 0;
Table{3,4} = 1;
Table{4,4} = 0;
Table{5,4} = 1;

1 个答案:

答案 0 :(得分:1)

如果将单元格矩阵转换为表格,如下所示:

T = cell2table(C(2:end,:));
T.Properties.VariableNames = C(1,:);

然后,您可以使用findgroupssplitapply来获得所需的结果:

G = findgroups(T.Datetime);
res = cell2mat(splitapply(@(x){Process(x)},T.ZeroAndOne,G));
T.OneForFirstTime = res(:,1);
T.OneForLastTime = res(:,2);

function res = Process(x)
    res = zeros(numel(x),2);
    res(find(x,1,'first'),1) = 1;
    res(find(x,1,'last'),2) = 1;
end

通过根据日期将表拆分为组,然后在每个单独的组上应用指定的逻辑来完成该过程。这是结果:

 Datetime      ZeroAndOne    OneForFirstTime    OneForLastTime
___________    __________    _______________    ______________

01-Jan-1999    1             1                  0             
01-Jan-1999    1             0                  1             
05-Jan-1999    0             0                  0             
05-Jan-1999    1             1                  1            

无论为每个日期分配了多少条目,这都有效(我不知道每个唯一日期是否只允许两个条目,您的示例在这个观点上可能会有点误导):

% Example...
C = cell(7,2);
C{1,1} = 'Datetime';
C(2,1) = num2cell(datetime('01.01.1999','InputFormat','dd.MM.yyyy'));
C(3,1) = num2cell(datetime('01.01.1999','InputFormat','dd.MM.yyyy'));
C(4,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));
C(5,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));
C(6,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));
C(7,1) = num2cell(datetime('05.01.1999','InputFormat','dd.MM.yyyy'));
C{1,2} = 'ZeroAndOne';
C{2,2} = 1;
C{3,2} = 1;
C{4,2} = 0;
C{5,2} = 1;
C{6,2} = 0;
C{7,2} = 1;

% My code for converting the cell into a table...
% My code for calculating the two additional rows...

输出:

 Datetime      ZeroAndOne    OneForFirstTime    OneForLastTime
___________    __________    _______________    ______________

01-Jan-1999    1             1                  0             
01-Jan-1999    1             0                  1             
05-Jan-1999    0             0                  0             
05-Jan-1999    1             1                  0             
05-Jan-1999    0             0                  0             
05-Jan-1999    1             0                  1