2

In MATLAB say I have an array, and have created a logical vector that has true entries for elements that I want to remove, call it del_index for example. To accomplish this, is one of the following ways better/faster and/or preferable?

arr(del_index) = [];

OR

arr = arr(~del_index);
Chris Gordon
  • 191
  • 3
  • 13
  • related: http://stackoverflow.com/questions/27657685/what-is-the-fastest-way-of-appending-an-element-to-an-array – jub0bs Jun 30 '15 at 19:55

1 Answers1

1

Both look nice, so lets test the speed.

time1=0;
th=0.5
for ii=1:100000

   arr=rand(10000,1);
   del_index=arr<th;
   tic
   arr(del_index) = [];
   time1=time1+toc;
end


time2=0;
for ii=1:100000

   arr=rand(10000,1);
   del_index=arr<th;
   tic
   arr = arr(~del_index);
   time2=time2+toc;
end

display(['arr(del_index) is ', num2str(time1/time2), ' times slower'])

I tried with different values of th, from 0 to 1 and I generally get this value. So yeah, second on is better.

arr(del_index) is 1.5136 times slower

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120