using find(ismember) instead of a loop?

2 ビュー (過去 30 日間)
wesso Dadoyan
wesso Dadoyan 2016 年 10 月 4 日
編集済み: Guillaume 2016 年 10 月 4 日
I have matrix B which is has around 1 million rows and Matrix A which has 800,000 rows. I want to match the observations of A and B and then assign to A the observations of B that matches. I tried a loop which taking forever in terms of time. I am wondering if I can do it in one shot using find(ismember). below are my codes:
for i=1:size(B,1)
x0=find(A(:,2)==B(i,2) & A(:,1)==B(i,1));
B(i,8)=A(x0,9);
end
  2 件のコメント
Matt J
Matt J 2016 年 10 月 4 日
編集済み: Matt J 2016 年 10 月 4 日
I suspect you haven't shown your actual code, making it hard to interpret what you are trying to do. In the posted code, you are comparing columns of A with rows of B which should be producing errors like the following, unless you are using R2016b
>> [1 2 3] == [1;2;3]
Error using ==
Matrix dimensions must agree.
Also, the code you've shown uses only the 1st, 2nd, and 9th column of A. So, why is it significant that "A has 800000 rows"?
wesso Dadoyan
wesso Dadoyan 2016 年 10 月 4 日
I am not receiving any error. the size is significant to show that the loop takes a lot of time . i need a one step approach rather than a loop.

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

採用された回答

Guillaume
Guillaume 2016 年 10 月 4 日
編集済み: Guillaume 2016 年 10 月 4 日
Note that the find was completely unnecessary in your original example, you could just have used the logical array returned by the comparison:
x0=A(:,2)==B(i,2) & A(:,1)==B(i,1);
B(i,8)=A(x0,9); %would have worked exactly the same with marginal speed gain.
To answer your question:
[found, Arow] = ismember(B(:, 1:2), A(:, 1:2), 'rows');
B(found, 8) = A(Arow(found), 9);

その他の回答 (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