Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Avoid for loops with if inside

Asked by hung lequang on 4 Oct 2012

*Hello everyone,

Can anyone show me how I can avoid following for loops, so that my run can be much faster? Any help is highly appreciated. Thanks!*

          c2=0.7;
          c1=0.3;
          x1=rand(1,100)*10;
          x3=rand(1,100)*10;
          x3p=rand(1,100)*10;
          x=[0.0000,0.2560,0.4980,0.7590,1.0000,1.2400,1.5000,1.7600,2.0100];
          y=[0.3,0.133,0.0777,0.0695,0.0920,0.1078,0.0829,0.0807,0.0936];
          for ix1=1:length(x1)
               for ix3=1:length(x3)                   
                   for ix3p=1:length(x3p)
                       r= sqrt(x1(ix1)^2 + (x3(ix3)-x3p(ix3p))^2);
                       if r <= 10
                          g = fit(x',y','splineinterp');
                          Prs_22x(ix1,ix3,ix3p)= c2-c1+g(r/R);
                       else
                          Prs_22x(ix1,ix3,ix3p)= c2-c1+c1^2;
                       end
                   end                    
               end
          end

0 Comments

hung lequang

Products

No products are associated with this question.

1 Answer

Answer by Matt Fig on 4 Oct 2012
Edited by Matt Fig on 4 Oct 2012
Accepted answer

Just taking this outside all loops will GREATLY speed it up.

g = fit(x',y','splineinterp');

Beyond that, you could do this (I assume R is a scalar):

P = bsxfun(@(x,y) (x-y),x3,reshape(x3p,1,1,numel(x3p)));
P = bsxfun(@(x,y) sqrt(x.^2+y.^2),x1.',P);
I = P<=10;
P(I) = c2-c1+g(P(I)/R);
P(~I) = c2-c1+c1^2;

1 Comment

hung lequang on 4 Oct 2012

Thank you very much.

Matt Fig

Contact us