简体   繁体   English

如何在Matlab中将向量与异步时间戳对齐?

[英]How to align vectors with asynchronous time stamp in matlab?

I would like to align and count vectors with different time stamps to count the corresponding bins. 我想对齐并计算带有不同时间戳的向量以计算相应的bin。

Let's assume I have 3 matrix from [N,edges] = histcounts in the following structure. 假设我在以下结构中有3个矩阵,它们由[N,edges] = histcounts组成。 The first row represents the edges, so the bins. 第一行代表边缘,因此代表垃圾箱。 The second row represents the values. 第二行代表值。 I would like to sum all values with the same bin. 我想用同一个bin汇总所有值。

A = [0 1 2 3 4 5;
     5 5 6 7 8 5]

B = [1 2 3 4 5 6;
     2 5 7 8 5 4]

C = [2 3 4 5 6 7 8;
     1 2 6 7 4 3 2]

Now I want to sum all the same bins. 现在,我想对所有相同的箱进行求和。 My final result should be: 我的最终结果应该是:

result = [0 1 2 3 4 5 6 7 8;
          5 7 12 16 ...]

I could loop over all numbers, but I would like to have it fast. 我可以遍历所有数字,但我想尽快处理。

You can use accumarray : 您可以使用accumarray

H = [A B C].';   %//' Concatenate the histograms and make them column vectors

V = [unique(H(:,1)) accumarray(H(:,1)+1, H(:,2))].';   %//' Find unique values and accumulate

V =

    0    1    2    3    4    5    6    7    8
    5    7   12   16   22   17    8    3    2

Note: The H(:,1)+1 is to force the bin values to be positive, otherwise MATLAB will complain. 注意: H(:,1)+1将强制bin值为正,否则MATLAB会抱怨。 We still use the actual bins in the output V . 我们仍然在输出V使用实际的bin。 To avoid this, as @Daniel says in the comments, use the third output of unique (See: https://stackoverflow.com/a/27783568/2732801 ): 为了避免这种情况,如@Daniel在评论中所述,请使用unique第三个输出 (请参阅: https ://stackoverflow.com/a/27783568/2732801):

H = [A B C].';  %//' stupid syntax highlighting :/
[U, ~, IU] = unique(H(:,1));
V = [U accumarray(IU, H(:,2))].';   

If you're only doing it with 3 variables as you've shown then there likely aren't going to be any performance hits with looping it. 如果您仅使用显示的3个变量进行处理,则循环执行可能不会对性能产生任何影响。

But if you are really averse to the looping idea, then you can do it using arrayfun . 但是,如果您真的不喜欢循环的想法,那么可以使用arrayfunarrayfun

rng = 0:8;
output = arrayfun(@(x)sum([A(2,A(1,:) == x), B(2,B(1,:) == x), C(2,C(1,:) == x)]), rng);

output = cat(1, rng, output);

    output =

        0     1     2     3     4     5     6     7     8
        5     7    12    16    22    17     8     3     2

This can be beneficial for particularly large A , B , and C variables as there is no copying of data. 这对于特别大的ABC变量可能是有益A ,因为没有数据复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM