How to vectorize this code with logical idexing

Hi all,
I have the following code, how can I avoid the for to make it faster?
a=[10:5:50];
b=[10:20:50];
c=rand(size(a));
for i=length(b)-1
d=c(a>=b(i) & a<b(i+1));
end
thanks
cheers

1 件のコメント

Jos (10584)
Jos (10584) 2014 年 5 月 15 日
Since you're only storing the last values of d in each iteration, you can skip the for-loop completely:
i = length(b)-1
d = c(a>=b(i)) & a<b(i+1))
but I am pretty sure you intend to do something else.
What should happen with the values of d obtained in the iterations 1 to length(b)-2?

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

 採用された回答

Andrei Bobrov
Andrei Bobrov 2014 年 5 月 14 日
編集済み: Andrei Bobrov 2014 年 5 月 15 日

0 投票

a=[10:5:50];
b=[10:20:50];
c=rand(size(a));
[~,ii] = histc(a,b);
d = accumarray(ii(:),c(:),size(b(:)),@(x){x})

3 件のコメント

pietro
pietro 2014 年 5 月 15 日
編集済み: pietro 2014 年 5 月 15 日
Hi Andrei,
thanks. I tried with my code but the empty bins at the end of the array are skipped. Here an axample:
a=[10:5:20, 55:5:90];
b=[10:20:170];
c=rand(size(a));
[er,ii] = histc(a,b);
d = accumarray(ii(:),c(:),[],@(x){x});
d should be a 8 elements array instead it is 4 elements array. How could I do to take into account the empty bins at the end of the array?
Andrei Bobrov
Andrei Bobrov 2014 年 5 月 15 日
corrected
pietro
pietro 2014 年 5 月 15 日
It works. Thanks

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

製品

タグ

質問済み:

2014 年 5 月 14 日

コメント済み:

2014 年 5 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by