How do you vectorize the following for loop?

1 回表示 (過去 30 日間)
Ben
Ben 2013 年 7 月 13 日
I'm trying to vectorize this for loop. A and B are both vectors. The general idea is that D should be a vector made up of 0's and 1's whenever an element of B matches A. For example, since B(3)=6 and A(6)=6, D(6) should be equal to 1. Here's the non-vectorized (correct) code:
A=[1:10]'; B=[1 2 6 9]'; D=zeros(length(A),1);
for i=1:length(B) C=(A==B(i)); D=D+C; end
My initial guess at vectorization was this: (NOTE: this code is incorrect)
A=[1:10]'; B=[1 2 6 9]'; D=(A==B);
The error comment I get after running the incorrect code is: Error using == Matrix dimensions must agree.
Thanks ahead of time, and if I'm unclear in anyway, I'd gladly clarify.

採用された回答

Image Analyst
Image Analyst 2013 年 7 月 13 日
Use ismember()
A=[1:10]'
B=[1 2 6 9]'
D = ismember(A, B)

その他の回答 (0 件)

カテゴリ

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