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

Selecting specific values in a for loop, when a certain condition hold true

Asked by Nathan Edge on 11 Oct 2011

Hello, i've written the following script in MATLAB:

Rcon=(Rmax^2) -(Rmin^2);
Ccon= cosd(Thetamin) - cosd(Thetamax);
vN = linspace(0, 180, N);
vP = linspace(Thetamin, Thetamax, P);
for iN = 1:length(vN)
  Phi = vN(iN);
  G(iN)=Phi + BOC;
  C2(iN)=Rcon / ((Ccon * cosd(G(iN))) + (Scon * sind(G(iN))));
  C1(iN)=Rmax^2 + (C2(iN) * cosd(G(iN) + Thetamax));
  A(iN)= (sqrt(C1(iN)+C2(iN)) + sqrt(C1(iN)-C2(iN)))./2;
  B(iN)=C2(iN) / (2*A(iN));
      for iP = 1:length(vP)
        Theta = vP(iP);
        R(iP)= sqrt(abs(C1(iN) - (C2(iN) * cosd(G(iN) + Theta))));
        F(iN,iP)= abs(((R(iP)*(M*g*L)) *cosd(Theta)) / ...
                      ((A(iN)*B(iN)) * sind(G(iN)+Theta)));
        Ffinal =max(F);

this script is designed to extract certain values for F as the values for phi and Theta change, where Phi runs from 0 to 180 for a certain number of inputted values (N), and theta lies within P input values, Thetamin and Thetamax. The variable R is also subject to changes in Phi and theta: however, in reality, we know that R falls within a certain range of values (between a maximum, Rmax, and a minimum, Rmin). I have found that with some values of Phi and Theta, the calculated values for R (line 20, including spaces) fall outside of this known range. I'd like to run the script so that I will only calculate F if the calculated value for R falls within the known range. I have attempted to use this command at line 21, but without success:

if Rmin<R(iP) && R(iP)<Rmax

Does anybody have any advice?



1 Comment

Jan on 11 Oct 2011

Maybe an obvious question: What are the values of Rmin and Rmax? Is Rmin actually smaller then Rmax?

Also, how do you know it is without success? What is the result of your change?

Nathan Edge


No products are associated with this question.

1 Answer

Answer by Andrei Bobrov on 11 Oct 2011
Accepted answer
for iP = 1:length(vP)
   Theta = vP(iP);
   R(iP)= sqrt(abs(C1(iN) - (C2(iN) * cosd(G(iN) + Theta))));
   if R(iP) >= Rmin && R(iP) <= Rmax
       F(iN,iP)= abs(((R(iP)*(M*g*L)) *cosd(Theta)) / ...
                      ((A(iN)*B(iN)) * sind(G(iN)+Theta)));
       F(iN,iP) = nan;
   Ffinal =max(F);


Andrei Bobrov

Contact us