フィルターのクリア

Vectorizing the creation of an offset vector

4 ビュー (過去 30 日間)
Matthias
Matthias 2013 年 5 月 22 日
Is there any possibility to vectorize this piece of code:
BIN_1 = 7;
C = randi(10,1000,1);
offset_vec = zeros(size(C));
delete = [];
o = 0;
for i = 1:size(C)
if C(i) == BIN_1
o = o + 1;
delete = [delete, i];
end
offset_vec(i) = o;
end
It creates an offset vector, which increases whenever the corresponding element in C equals 7. The for-loop seem very slow.

採用された回答

Andrei Bobrov
Andrei Bobrov 2013 年 5 月 22 日
編集済み: Andrei Bobrov 2013 年 5 月 22 日
ii = find(C == BIN_1);
offset_vec = zeros(size(C));
offset_vec(ii) = 1;
offset_vec = cumsum(offset_vec);
or (ADD)
t = C == BIN_1;
offset_vec = cumsum(t);
ii = find(t); % analog of 'delete'
  2 件のコメント
Jan
Jan 2013 年 5 月 22 日
Slightly faster: Omit the find() and use logical indexing.
Andrei Bobrov
Andrei Bobrov 2013 年 5 月 22 日
Hi Jan! I agree with you. Added.

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

その他の回答 (1 件)

Jan
Jan 2013 年 5 月 22 日
Some comments:
1. Letting a vector grow iteratively is a severe waste of time. Note, that if delete is a 1x1000 vector finally, the iterative construction demands for reverving sum(1:1000) elements any copying almost the same number of elements. Better:
delete = false(1, numel(C));
o = 0;
for i = 1:numel(C)
if C(i) == BIN_1
delete(i) = true;
...
2. size(C) replies a vector. Therefore for i = 1:size(C) might perform unexpected things. Better use (as shown in the code above already) numel(C) or size(C, 1) (or what ever you need exactly).
  1 件のコメント
Matthias
Matthias 2013 年 5 月 22 日
I know that growing Arrays are pretty slow, but the Finale size of the Array is somewhere around 100, while the for loop has several million iterations. That's why I believe it doesn't really matter in this specific case.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by