A vectorizing lesson

34 views
Skip to first unread message

reza mehrabadi

unread,
Feb 2, 2019, 10:43:20 AM2/2/19
to YALMIP
Hi. for many users adapted to GAMS code structure (working with "sets"), writing the "sums" and "equations" in MATLAB may be a hard task without using the "for" loops (However using nested "for" loops eats a lot of time in running the code). As you know the trick is vectorizing the equations. Although it takes more effort that GAMS (because finding the indexes for each variable/parameter requires an additional piece of code) but it saves time in complex models with high number of variables, consider the equation below:

constraints=[constraints,p(i,j,t,h)==b(i,j)*(d(i,t,h)-d(j,t,h))];    %b as a parameter

without using "for", a common way (that works in many cases like this example) to vectorization is to find the indice related to each (i,j,t,h), (i,j) , ...
using the code below and saving the resultant matrices:
  k=1;
   for i=1:I
   for j=1:J
    for t=1:T
     for h=1:H   
      indexp(1,k)=sub2ind([I J T H],i,j,t,h);
      indexb(1,k)=sub2ind([I J],i,j);
      indexd1(1,k)=sub2ind([I t H],i,t,h);
      indexd2(1,k)=sub2ind([J T H],j,t,h);
      k=k+1;
     end
    end
   end
  end
Now we have all required indice numbers and the equation can be written as follow (Notice that the above code is needed to run just one time and then saving the indexes matrices):
 
constraints=[constraints,p(indexp(1,:))==b(indexb(1,:)).*(d(indexd1(1,:))-d(indexd2(1,:)))];

Reply all
Reply to author
Forward
0 new messages