在Java中实现滑动时间窗口

时间:2014-12-22 12:17:15

标签: java csv sliding-window

我有一个以下结构的csv文件:

  

时间(毫秒)," x"," y"," z"

     

1389776970139" -0.042138"" 0.0531513"" 8.28537"

     
    

........

  
     

1389776970833" -0.0124942"" -0.00338816"" 0.704891"

我使用ArrayList将csv文件的每个数据集(时间,x,y,z)保存为对象。现在我想在两秒的滑动时间窗口内单独计算x,y,z的平均值,其中一秒重叠。

我希望我的问题直截了当,如果不是,请告诉我,以便重新解释我的问题。

我是Java的新手,我不知道如何实现这样的想法。我会非常感谢任何想法。

提前致谢!!!

最好的问候, 迈克尔

1 个答案:

答案 0 :(得分:2)

好的,让我用“即兴伪代码”来写它,因为你说你只需要一个想法而不是现成的解决方案,我认为你自己实现它会更有趣:

strings_array[][4];   // dynamic array of arrays; outer array's elements are strings of your CSV file
                      // and inner array has 4 elements corresponding for time, x, y and z
results_array[][4];   // same type of array to store results: final timestamp of each window
                      // and respective averages for x, y and z
start_time = strings_array[0][0]; // saving starting time
sum_coord[3] = {0,0,0};            // array to store sum of each of the x, y and z
points_num = 0;                    // variable to store number of time points in the current window
line_num = 0;                      // variable to store number of lines processed
while (line_num < strings_array.length) {  // iterating over outer part of strings_array - i.e. over
                                           // lines of original CSV file
    string_arr = strings_array[line_num];  // storing current line of CSV file
    line_num++;                            // incrementing total number of lines processed
    if (string_arr[0] < start_time+2000) { // if end of the window is not reached yet
        for (i=0; i<3; i++)
            sum_coord[i] += string_arr[i]; // adding each of x, y and z to the sum of the window
        points_num++;                      // incrementing number of time points in the window
        continue;                          // go to the next line of CSV file
    }
    // if, on the other hand, we have exceeded the window
    // storing averages for the window
    if (points_num == 0)
        results_array.append({start_time, 0, 0, 0});
    else
        results_array.append({start_time, sum_coord[0]/points_num, sum_coord[1]/points_num, sum_coord[2]/points_num});
    sum_coord = {0, 0, 0};                 // resetting each of x, y and z sums of the window
    points_num = 0;                        // resetting number of time points in the window
    while (strings_array[line_num-1][0] >= start_time+1000)  // going back 1 sec until we find start of the next window
        line_num--;
    start_time+=1000;  // resetting beginning of the window (make sure it's what you mean!)
                       // otherwise, can do: start_time = strings_array[line_num-1][0]
                       // to have next window based on the last timepoint within 1 sec
}