我正在使用Matlab,我在过滤矩阵方面遇到了问题。矩阵填充了数字上升,我想删除矩阵中的所有条目,这些条目比给定的intervall更接近于(n-1)之前的条目。
我已经使用for循环完成了这项工作。问题是,计算了五个小时!
我的代码:
for i=2:y
if ((arrMaster1(i-1)+deadtime)<arrMaster1(i))
j=j+1;
arrMaster1cut(j,3)=int64(arrMaster1(i));
else
end
end
答案 0 :(得分:1)
首先,您可以一次完成所有减法操作,而不是每个循环中的单个元素。使用diff
就可以更轻松地实现这一点
diffs = diff(arrMaster1(1:y));
% equivalent to: diffs = arrMaster1(2:y) - arrMaster1(1:y-1);
然后创建一个逻辑数组,以测试您的差异是否大于deadtime
:
keepthese = [true, diffs > deadtime];
% outputs vector like [1 0 1 1 1 0 ...], of length y, where 1 is true and 0 is false
% diffs is of length y-1, so extra "true" is needed.
% There is a "true" in the place of every element you want to keep.
最后,创建输出:
arrMaster1cut = int64(arrMaster1(keepthese));
% This is called logical indexing, you're choosing all elements of
% arrMaster1 where keepthese has the value 1 / true
一起:
diffs = diff(arrMaster1(1:y)); % Get differences for tolerencing
keepthese = [true, diffs > deadtime]; % Get indices to keep
arrMaster1cut = int64(arrMaster1(keepthese)); % Create output
修改记事
keepthese
向量是行向量,因此与逗号连接。如果arrMaster1
是列向量,那么diffs
也是如此,所以改为使用分号
keepthese = [true; diffs > deadtime]; % Get indices to keep (column vector)
有关索引的说明
逻辑索引与正常索引。假设我们想从5元素矩阵中拉出第1,第2和第4个元素。我们可以使用两种方法:
elements = mymatrix([1,2,4]);
elements = mymatrix(logical([1,1,0,1,0])); % logical converts 1/0 to true/false
显然,第二种方法(逻辑索引)在这个例子中并不清楚。但是,当在上面使用时,它允许我们避免调用find
函数,这会将逻辑索引转换为编号向量:
find([1,1,0,1,0]); % = [1,2,4]
因此,我们获得了速度优势。
答案 1 :(得分:0)
我没有你所有的代码,所以这只是猜测,但你的代码可能运行得很慢,因为你没有为arrMaster1cut
预先分配内存,而是在每次迭代中改变它的大小。
此外,您可以使用diff
来对整个代码进行矢量化:
% random arrMaster1 array
y = 100;
arrMaster1 = randi(100,[1 y]);
deadtime = 5;
% differences vector
d = diff(arrMaster1);
% differences greater than deadtime
idxs = find(d > deadtime);
% produce arrMaster1cut
arrMaster1cut1 = int64(arrMaster1(idxs+1));
% your method
j = 0;
arrMaster1cut2 = [];
for i=2:y
if ((arrMaster1(i-1)+deadtime)<arrMaster1(i))
j=j+1;
arrMaster1cut2(j)=int64(arrMaster1(i));
else
end
end
% check for equal results
isequal(arrMaster1cut2, arrMaster1cut1)