通过 = [] 删除矩阵元素 vs 重新分配矩阵 [英] 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!
这篇关于通过 = [] 删除矩阵元素 vs 重新分配矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!