MATLAB: How to use if inside loop

for loopif statementloop

I'm working on matlab code for counting number of reflection, here is my code
RY=30;
L_B=40;
L_S=20;
% Single Reflection Left Side
if RY < 2*L_B
R1L=1 % 1
elseif 2*L_B<RY && RY< 2*(L_B+L_S)
R1L=0 % 3
elseif 2*(L_B+L_S) < RY && RY< 2*(2*L_B+L_S)
R1L=1 % 5
elseif 2*(2*L_B+L_S) < RY && RY< 2*(2*L_B+2*L_S)
R1L=0 % 7
elseif 2*(2*L_B+2*L_S) < RY && RY< 2*(3*L_B+2*L_S)
R1L=1 % 9
elseif 2*(3*L_B+2*L_S) < RY && RY< 2*(3*L_B+3*L_S)
R1L=0 % 11
elseif 2*(3*L_B+3*L_S) < RY && RY< 2*(4*L_B+3*L_S)
R1L=1 % 13
else
R1L=0
end
% Single Reflection Right Side
if RY < 2*L_B
R1R=1 % 2
elseif 2*L_B<RY && RY< 2*(L_B+L_S)
R1R=0 % 4
elseif 2*(L_B+L_S) < RY && RY< 2*(2*L_B+L_S)
R1R=1 % 6
elseif 2*(2*L_B+L_S) < RY && RY< 2*(2*L_B+2*L_S)
R1R=0 % 8
elseif 2*(2*L_B+2*L_S) < RY && RY< 2*(3*L_B+2*L_S)
R1R=1 % 10
elseif 2*(3*L_B+2*L_S) < RY && RY< 2*(3*L_B+3*L_S)
R1R=0 % 12
elseif 2*(3*L_B+3*L_S) < RY && RY< 2*(4*L_B+3*L_S)
R1R=1 % 14
else
R1R=0
end
Total=R1L+R1R
When it is executed, Total=2
However, I want to change variable RY to from 1 to 200 with step=1 so the size of Total is 200×1 How I supposed to do with looping?

Best Answer

I think the following will solve your problem.
Total = zeros(200,1);
for kk = 1:200
RY = kk;
L_B=40;
L_S=20;
% Single Reflection Left Side
if RY < 2*L_B
R1L=1; % 1
elseif 2*L_B<RY && RY< 2*(L_B+L_S)
R1L=0; % 3
elseif 2*(L_B+L_S) < RY && RY< 2*(2*L_B+L_S)
R1L=1; % 5
elseif 2*(2*L_B+L_S) < RY && RY< 2*(2*L_B+2*L_S)
R1L=0; % 7
elseif 2*(2*L_B+2*L_S) < RY && RY< 2*(3*L_B+2*L_S)
R1L=1; % 9
elseif 2*(3*L_B+2*L_S) < RY && RY< 2*(3*L_B+3*L_S)
R1L=0; % 11
elseif 2*(3*L_B+3*L_S) < RY && RY< 2*(4*L_B+3*L_S)
R1L=1; % 13
else
R1L=0;
end
% Single Reflection Right Side
if RY < 2*L_B
R1R=1; % 2
elseif 2*L_B<RY && RY< 2*(L_B+L_S)
R1R=0; % 4
elseif 2*(L_B+L_S) < RY && RY< 2*(2*L_B+L_S)
R1R=1; % 6
elseif 2*(2*L_B+L_S) < RY && RY< 2*(2*L_B+2*L_S)
R1R=0; % 8
elseif 2*(2*L_B+2*L_S) < RY && RY< 2*(3*L_B+2*L_S)
R1R=1; % 10
elseif 2*(3*L_B+2*L_S) < RY && RY< 2*(3*L_B+3*L_S)
R1R=0; % 12
elseif 2*(3*L_B+3*L_S) < RY && RY< 2*(4*L_B+3*L_S)
R1R=1; % 14
else
R1R=0;
end
Total(kk)=R1L+R1R
end