Path: news.mathworks.com!not-for-mail From: <HIDDEN> Newsgroups: comp.soft-sys.matlab Subject: Re: Speeding Up Code Date: Tue, 7 Jun 2011 15:51:20 +0000 (UTC) Organization: The MathWorks, Inc. Lines: 45 Message-ID: <islhdo$k9d$1@newscl01ah.mathworks.com> References: <isk6s3$r2a$1@newscl01ah.mathworks.com> Reply-To: <HIDDEN> NNTP-Posting-Host: www-01-blr.mathworks.com Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: newscl01ah.mathworks.com 1307461880 20781 172.30.248.46 (7 Jun 2011 15:51:20 GMT) X-Complaints-To: news@mathworks.com NNTP-Posting-Date: Tue, 7 Jun 2011 15:51:20 +0000 (UTC) X-Newsreader: MATLAB Central Newsreader 1187260 Xref: news.mathworks.com comp.soft-sys.matlab:730640 "Yvette Hammond" wrote in message <isk6s3$r2a$1@newscl01ah.mathworks.com>... > Hi, > > I have the folllowing type of loop several times in my code and three of the lines are slowing my code down massively: > > B=zeros(length(ID),1); > r_i=zeros(1,1); > for i=1:1:length(ID) > > r_i=find(mat1(:,1)==ID(i,1)); > if isempty(r_i) > B(i,1)=0; > > else > > B(i,1) = r_i; > > if max(B)==0 > B1=0; > else > B1=B(B~=0); > end > end > end > > The <mx1> matrix 'ID' contains a list of numbers that I want to search for in the <px2> matrix 'mat1'. I want B1 to be an ordered list of the rows in 'mat1' where each number in 'ID' occurs (if it occurs at all). All numbers in 'mat1(:,1)' are unique and occur only once, the numbers in 'ID' may repeat. 'mat1' may not contain every number in 'ID'. > > The three lines that are taking the longest to compute are (in order of longest to shortest) 'B1=B(B~=0);', 'r_i=find(mat1(:,1)==ID(i,1));' and 'if max(B)==0'. > > Any ideas on how to speed up the above code would be very much appreciated, I have been struggling with this for a long time! > > Thanks in advance, > > Yvette - - - - - - - - - The five-line if-else-end sequence involving B1 looks completely misplaced. It keeps overwriting all its previous computations in the for-loop, so therefore it ought to be done after the for-loop finishes where it would only be performed once. However, there is a function, 'ismember', that can calculate B much more efficiently: [t,B] = ismember(ID,mat1(:,1)); B1 = sort(B(t)); I have interpreted your phrase "I want B1 to be an ordered list" to mean you wanted the B1 indices of B to be in ascending order. That would not be accomplished in your code. Roger Stafford