Eliminating a FOR loop

1 回表示 (過去 30 日間)
Scott
Scott 2014 年 9 月 2 日
編集済み: Andrei Bobrov 2014 年 9 月 2 日
I am trying to eliminate a FOR loop to improve speed. The problem I am working with involves evaluating each element of an array with each element of a matrix. Below is a simplified example of what I am trying to do.
I have two matrices:
A = [a11 a12 a13;a21 a22 a23; a31 a32 a33];
B = [b1 b2 b3 b4];
What I would like to do is evaluate each element of B against each element of A. For example
for i=1:1:4
[I,J] = find(B(i)==A(:,:));
end
Is there a way to do this without a FOR loop.
Thanks in advance,
Scott
  1 件のコメント
Guillaume
Guillaume 2014 年 9 月 2 日
編集済み: Guillaume 2014 年 9 月 2 日
Your example overwrites I and J on each pass of the loop, so it's not clear what you want out. Did you mean:
[I{i} J{i}] = find(B(i)==A);

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

採用された回答

Matt J
Matt J 2014 年 9 月 2 日
編集済み: Matt J 2014 年 9 月 2 日
L=bsxfun(@eq,A(:),B(:).');
L=reshape(L,[size(A),length(B)]);
[I,J,~]=ind2sub(size(L),find(L));
  1 件のコメント
Scott
Scott 2014 年 9 月 2 日
Matt,
Thank you very much. Your answer was exactly what I was looking for.

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

その他の回答 (4 件)

Iain
Iain 2014 年 9 月 2 日
The function you might be looking for is probably
intersect

Pierre Benoit
Pierre Benoit 2014 年 9 月 2 日
編集済み: Pierre Benoit 2014 年 9 月 2 日
[~,idx] = ismember(B,A);
[I,J] = ind2sub(size(A),idx);

Guillaume
Guillaume 2014 年 9 月 2 日
You can use arrayfun or bsxfun to replace a loop. It's not necessary faster but may make the intent of the code clearer. In this case, assuming you want I and J as cell arrays, not so:
[I, J] = arrayfun(@(b) ind2sub(size(A), find(b==A)), B, 'uni', false);

Andrei Bobrov
Andrei Bobrov 2014 年 9 月 2 日
編集済み: Andrei Bobrov 2014 年 9 月 2 日
A = randi(10,5,6);
B = randi(10,4,1);
[i1,j1] = find(bsxfun(@eq,A,reshape(B,1,1,[])));
out_ij = [i1, rem(j1 - 1,size(A,2)) + 1];

カテゴリ

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