用= []与重新分配矩阵删除矩阵元素 [英] Deleting matrix elements by = [] vs reassigning matrix
问题描述
这两种在Matlab中删除元素的方法之间是否有区别:
Is there any difference between these two methods for deleting elements in Matlab:
ElementsToDelete = [0 0 1 0 1 0 0 1 1 0]
A = 1:10
A(ElementsToDelete) = []
%Versus
A = 1:10
A = A(~ElementsToDelete)
有没有一种方法比另一种更合适?效率上有区别吗?还是它们完全可以互换?
Are there times when one method is more appropriate than the other? Is there a difference in efficiency? Or are they completely interchangeable?
推荐答案
尝试一下:
A = rand(1e3, 1);
b = A<0.5;
tic;
for ii = 1:1e5
a = A;
a(b) = [];
end
toc
tic;
for ii = 1:1e5
a = A;
a = a(~b);
end
toc
结果:
Elapsed time is 1.654146 seconds
Elapsed time is 1.126325 seconds
因此,差异是速度因数1.5,有利于重新分配.但是,这种情况更糟:
So the difference is a speed factor of 1.5 in favour of re-assigning. This however, is worse:
A = rand(1e4, 1);
stop = 0;
for jj = 1:10
a = A;
start = tic;
for ii = 1:1e5
a(a < rand) = [];
end
stop = stop + toc(start);
end
avg1 = stop/10
stop = 0;
for jj = 1:10
a = A;
start = tic;
for ii = 1:1e5
a = a(a > rand);
end
stop = stop + toc(start);
end
avg2 = stop/10
avg1/avg2
结果:
avg1 = 1.1740235 seconds
avg2 = 0.1850463 seconds
avg1/avg2 = 6.344485136963019
因此,该因子增加到了6以上.
So, the factor's increased to well over 6.
我的猜测是删除(即用[]
赋值)通过逻辑索引在内部循环中每次出现true
时都会重写整个数组.这是无可救药的,效率低下,就像这样测试时很明显.另一方面,重新分配可以事先确定新数组的大小,并相应地对其进行初始化.无需重写.
My guess is that deletion (i.e., assigning with []
) re-writes the entire array on each and every occurrence of a true
in the internal loop through the logical indices. This is hopelessly inefficient, as becomes apparent when testing it like this. Re-assigning on the other hand can determine the size of the new array beforehand and initialize it accordingly; no re-writes needed.
为什么JIT不能将其中一个编译为另一个对我来说是个谜,因为删除是一种更加直观的表示法恕我直言.但是,如您所见,与替代方法相比,它效率低下,因此应谨慎使用. 切勿在循环内使用它!
Why the JIT does not compile the one into the other is a mystery to me, because deletion is a far more intuitive notation IMHO. But, as you see, it is inefficient compared to alternatives, and should thus be used sparingly. Never use it inside loops!
这篇关于用= []与重新分配矩阵删除矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!