From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Can this run any faster?
Date: Wed, 10 Apr 2013 04:46:09 +0000 (UTC)
Organization: The MathWorks, Inc.
Lines: 54
Message-ID: <kk2qqh$158$>
References: <kk24q4$3j5$>
Reply-To: <HIDDEN>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1365569169 1192 (10 Apr 2013 04:46:09 GMT)
NNTP-Posting-Date: Wed, 10 Apr 2013 04:46:09 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 1187260
Xref: comp.soft-sys.matlab:793118

"Elnaz " <> wrote in message <kk24q4$3j5$>...
> Hi all, 
> Is there any way to make this excerpt of the code run faster?
> In my script I call the function including this loop many times and "length" is in the order of 30K or more. "transitions" is a stored 32 by 4 matrix. 
> I have turned that function into C and am using it as a mex file but it's still prohibitively slow. 
> Using tic-toc I see that this loop is the most time consuming loop in that function. Is there anyway to make this run faster?
> a=zeros(16,length);
> a=a-inf;
> a(1,1)=0; 
> for i= 2:length
>      for j= 1:32
>            A = a(transitions(j,2),i);
>            B = a(transitions(j,1),i-1) + ug(j, i-1) + eg(j, i-1);
>            if(A == -inf && B == -inf)
>               a(transitions(j,2),i) = -inf;
>            else
>               a(transitions(j,2),i) = max(A,B) + log(1+exp(-abs(A-B)));   
>            end
>       end
> end
> Thanks,
> Elnaz
- - - - - - - - -
  You might try the following.  (I am assuming 'ug' and 'eg' are always finite.)

 a=zeros(16,length); % <-- Don't use "length". It's the name of a matlab function
 t1 = transitions(j,1); %<-- Avoid needless indexing in the loops
 t2 = transitions(j,2);
 ue = ug+eg; % <-- Do this addition ahead of time
 for i= 2:size(a,2)
   for j= 1:32
     k = t2(j);
     A = a(k,i);
     B = a(t1(j),i-1);
     if B ~= -inf
       B = B + ue(j,i-1);
       if A ~= -inf
         a(k,i) = max(A,B) + log(1+exp(-abs(A-B)));
         a(k,i) = B;

  The reasoning here is that in case B is equal to -inf, your code will not alter a(k,i) at all and thus there is nothing to do.  In case B is not equal to -inf but A equals -inf, then a(k,i) will be set to B.  Hence there is only need to use the time consuming max-log-exp calculation when A and B are both finite.

  Whether all of this saves you a significant amount of time depends on how prevalent an index value of t2 is paired with more than one index value of t1, which are the only cases in which the max-log-exp call can be made, and on the number of columns of 'a' that tend to become finite on the average as the outer loop proceeds.

Roger Stafford