【问题标题】:Reducing a Matlab table with减少一个 Matlab 表
【发布时间】:2015-12-17 10:53:30
【问题描述】:

将每个时间戳多行的 MATLAB 表缩减为每个时间戳只有一行的表,同时将其他值合并到这一行中的最快方法是什么? (参见:前后示例)

由于我必须处理大量数据,有没有办法并行执行此操作(parfor,...)?

之前:

Timestamp  Value01   Value02   Value03
_________  _______   _______   _______

1001       01        02        []          
1001       []        []        []          
1001       []        []        03          
1002       []        []        07          
1002       []        09        []          
1003       04        01        []
1003       []        []        []         
1004       05        06        08 

之后:

Timestamp  Value01   Value02   Value03
_________  _______   _______   _______

1001       01        02        03          
1002       []        09        07          
1003       04        01        []         
1004       05        06        08 

【问题讨论】:

  • 你没有说这个表是如何存储的——作为矩阵还是作为单元格?
  • @smlq 在 MATLAB 中有一个叫做 table 的东西(从 2014b 左右开始),我猜他会使用它。矩阵是不可能的,因为它不支持空元素赋值[]
  • 是的,我使用的是matlab表格格式。
  • 也许最好的办法是有一个嵌入代码的例子来创建这样一个表
  • 请将您的 table 示例更改为实际的 MATLAB 代码,我们可以将其粘贴到 MATLAB 中以获取您的数据结构示例。此外,如果其中一个 Value 列对单个时间戳有多个值,会发生什么情况?

标签: matlab merge parallel-processing reduce


【解决方案1】:

我发现您的问题很有趣,并试图找到解决方案。现在想向您展示我的方法。

首先,我尝试使用union 函数,但它对tables 的使用让我有点困惑,所以我发现的唯一方法是将表转换为cellnumeric 数据,使用它并然后创建新表。

代码如下:

tab = table2cell(MyTable(:,2:end))                  % convert to cell
tab( cellfun('isempty',tab) ) = {[0]}               % replace [] with [0]
tab = cell2mat(tab)                                 % convert to numeric
t = MyTable(:,{'Timestamp'})                        % lets take a time
t = table2array(t)                                  % to numeric too
t = t - 1000
fun = @(x) sum( tab( find (t == x),:),1)            % find the sum of rows with the same time
arr = [1:t(end)]'   %'                              % how many sums we need
carr = arrayfun(fun, arr, 'uniformoutput',false)    
result = cell2mat(carr)

结果是:

 result =

 1     2     3
 0     9     7
 4     1     0
 5     6     8

最后一步 - 创建新表。这只是一个例子:

Value01 = result(:,1)
Value01 = num2cell(Value01)
Value01(find([Value01{:}]==0)) = {[]}
%... the same for Value02 and Value03
NewTable = table(1000+arr,Value01, Value02, Value03, 'VariableNames',{'Timestamp', 'v1','v2','v3'})


NewTable = 

Timestamp    v1     v2     v3 
_________    ___    ___    ___

1001         [1]    [2]    [3]
1002         []     [9]    [7]
1003         [4]    [1]    [] 
1004         [5]    [6]    [8]

我已经完成了这个答案我想到了你的数据......看起来它是strings - 因为你有01而不是1......但我仍然认为我的解决方案是正确的,只需要重写一点如果你真的有strings :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    • 2011-06-09
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多