Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How can I design these nested for loops so they run much faster?

2 ビュー (過去 30 日間)
Subhei
Subhei 2014 年 5 月 20 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hello everyone, in my matlab script I have taken two sets of data from excel and imported them as arrays in matlab. Now, I want to eliminate all of the rows in in the second larger array that do not have the same number as any of the elements in the second column of the first array.
Doesn't make sense? Let me give you an example.
Take for example you have just imported two matrices A and B that look something like this:
A= 26 100 1991 B= 45 125 1984
26 101 1991 45 558 1984
27 185 1992 45 778 1984
27 181 1992 46 181 1995
28 56 1981 47 101 1996
Then I would want to create a new matrix by sorting through A to determine which rows of B should be eliminated. When the operation is complete I should end up with a new matrix for B that is much smaller:
new_B= 46 181 1995
47 101 1996
This is the script I have written that does this operation:
k=1;
for n=1:length(A)
x=A(n,2);
for i=1:length(B)
if B(i,2)== x
new_B(k,1)=B(i,1);
new_B(k,2)=B(i,2);
new_B(k,3)=B(i,3);
k=k+1;
end
end
end
This turns out to be very slow when the length of A = 100,000 and the length of B= 700,000. Could someone help me optimize this piece of code? Thank you for the help :)

回答 (2 件)

Cedric
Cedric 2014 年 5 月 20 日
編集済み: Cedric 2014 年 5 月 20 日
B_new = B(ismember(B(:,2), A(:,2)),:) ;
should take a fraction of second with the sizes that you mention.

Yao Li
Yao Li 2014 年 5 月 20 日
You need to design a new algorithm. Why not pre-sort the 2nd column of A and B before the comparison? Or calculate the min and max value of the 2nd column of A and B, and remove some rows in advance.

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by