# Deleting elements from vector

138 ビュー (過去 30 日間)
Ondrej 2015 年 3 月 10 日

I am removing some elements from a (long) vector. I am wondering which is the faster method in general (or better per se). Removing elements directly or by assigning "truncated" vector to the old one? This is what I mean (idx_remove are logical indices):
1.
vec(idx_remove) = [];
or 2.
vec = vec(~idx_remove);
Thanks.

サインインしてコメントする。

### 採用された回答

Guillaume 2015 年 3 月 10 日
I would think that matlab's JIT compiler would reduce both to the same instructions, but the only way to know for sure is to time it on your machine with your version of matlab.
>>vlength = 200000;
>>idx_remove = logical(randi([0 1], 1, vlength));
>>srcvector = rand(1, vlength);
>>tic; vec = srcvector; vec(idx_remove) = []; toc
Elapsed time is 0.004964 seconds
>>tic; vec = srcvector; vec = vec(~idx_remove); toc
Elapsed time is 0.005631 seconds
>>tic; vec = srcvector; vec(idx_remove) = []; toc
Elapsed time is 0.006492 seconds
>>tic; vec = srcvector; vec = vec(~idx_remove); toc
Elapsed time is 0.006448 seconds
In the end though, does it matter? You're chasing after micro-optimisations here. I would favor code clarity to a minuscule gain in performance. For that reason, I would choose option 1 when modifying the vector, and option 2 to assign the shortened vector to a new variable.

サインインしてコメントする。

### その他の回答 (1 件)

Jan 2015 年 3 月 10 日
vec = CopyMask(vec, ~idx_remove);
The next version will allow to apply the not() implicitly, such that the calculation of a large inverted logical vector can be avoided.

サインインしてコメントする。

### カテゴリ

Find more on Source Control Integration in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by