首页 > 解决方案 > 当每行的列数可变时,如何从长格式转换为宽格式?(MATLAB)

问题描述

我有一个加速度测量值的时间序列数据集,其中有许多亚秒的测量值,但每秒记录的实际亚秒数是可变的。

所以我会从看起来像这样的东西开始:

约会时间 十二月秒 加速 X
1 .00 0.5
1 .25 0.5
1 .50 0.6
1 .75 0.5
2 .00 0.6
2 .40 0.5
2 .80 0.5
3 .00 0.5
3 .50 0.5
4 .00 0.6
4 .25 0.5
4 .50 0.5
4 .75 0.5

并尝试将其转换为宽格式,其中每行是一秒,列是对应于每一秒的小数秒。

子1 子2 子3 子4
.5 .5 .6 .5
.6 .5 .5
.5 .5
.6 .5 .5 .5

在代码中,这看起来像:

%Preallocate some space
Dpts_observations = NaN(13,3);

%These are the "seconds" number
Dpts_observations(:,1)=[1 1 1 1...
                        2 2 2...
                        3 3...
                        4 4 4 4];

%These are the "decimal seconds"
Dpts_observations(:,2) = [0.00 0.25 0.50 0.75...
                          0.00 0.33 0.66...
                          0.00 0.50 ...
                          0.00 0.25 0.50 0.75]

%Here's actual acceleration values
Dpts_observations(:,3) = [0.5 0.5 0.5 0.5...
                          0.6 0.5 0.5...
                          0.4 0.5...
                          0.5 0.5 0.6 0.4]

%I have this in a separate file but I have summary data that helps me
determine the row indexes corresponding to sub-seconds that belong to the same second and I use them to manually extract from long form to wide form.

%Create table to hold indexing information
Seconds = [1 2 3 4];
Obs_per_sec = [4 3 2 4];
Start_index = [1 5 8 10];
End_index = [4 7 9 13];
Dpts_attributes = table(Seconds, Obs_per_sec, Start_index, End_index);

%Preallocate new array
Acc_X = NaN(4,4);

%Loop through seconds
for i=1:max(size(Dpts_attributes))
   Acc_X(i, 1:Dpts_attributes.Obs_per_sec(i))=Dpts_observations(Dpts_attributes.Start_index(i):Dpts_attributes.End_index(i),3);
end

现在这正在工作,但速度很慢。实际上,我有一个包含数百万秒的庞大数据集,我希望可能有比我目前使用的更好的解决方案。我的数据都是数字,试图让一切尽可能快。

谢谢!

标签: performancematlabindexingreshape

解决方案


推荐阅读