动态附加和删除矢量中的元素

时间:2016-11-11 19:01:06

标签: python matlab

有没有办法动态添加元素,同时删除其中的一些元素?最好是在MATLAB中。

例如,我们说我正在传输来自传感器的数据。由于它将永远流式传输,我想仅保留向量的最后100个样本/元素。

2 个答案:

答案 0 :(得分:2)

您可以在python中尝试Queue模块:

from Queue import Queue

q=Queue()

to enque at back    :  q.put(x)
to deque from front :  q.get()

您可以在python中使用deque中的collections(如果您有一些提前要求):

from collections import deque

d = deque([])

to enque at back     : d.append(x)
to enque at front    : d.appendleft(x)
to deque from back   : d.pop()
to deqeue from front : d.popleft()

答案 1 :(得分:-1)

在Matlab中没有正式的queue数据结构,但您所描述的基本情况可以通过巧妙地使用索引和max来实现:

d = [];  % Allocate empty array
n = 100; % Max length of buffer/queue

% A loop example for illustration
for i = 1:1e3
    x = rand(1,3);                           % Data to append
    d = [d(max(end-n+1+length(x),1):end) x]; % Append to end, remove from front if needed
end

以上假设附加数据x是一个长度为0到n的行向量。您可以轻松地将其修改为附加到前面等。它也可以转换为函数。

您还可以在MathWorks文件交换中找到实现各种队列形式的类,例如this one

相关问题