MATLAB: If-statements within a for loop does not respond to the counter appropriate

for loopif statementvector

Hello, my if statements within my for loop does not work appropiate. When i'm printing the x-vector to the screen, the maximum value is sadly 25000 in x(i)
The counter only reach 1, but i'll like to count further if the condition name(i) & name1(i) holds. Name and name1 are also vectors with dimensions 100×1. Another concern is for instance when printing name(1) and name1(1) to the screen I've seen that the counter, op, runs despite that name1(1) is <10. Is the && command wrong?
x = zeros(100,1); %Preallocation
name1 = randi(30,100,1) %vector

name = randi(([0 1], 100,1) %vector
op=0; %counter index
for i=1:length(x)
if name(i)==1 && name1(i)>=10
op=op+1; %counter
else
if op~=0;
if 0<op<=1;
x(i)=x(i)+25000;
elseif 1<op<=2;
x(i)=x(i)+75000;
elseif 2<op;
x(i)=x(i)+200000;
end
op=0;
end
end
end

Best Answer

a<x<=b is not doing what you thing it's doing and is not the way to check that a number is between two numbers. What it does is check that a<x. This results in either false (0) or true (1). It then compares that 0 or 1 to b. When b is 1, this is always true, thus
0<op<=1
will always be true. The proper syntax is
0 < op && op <= 1
However, since you've already checked that op is not 0 and since it is integer you could just have
if op == 1
%...


elseif op == 2
%...
else
%...
end
Other comments
  • name1 and name seem like poor names for your variables. They certainly do not describe at all what these variables are used for.
  • ; are not needed at the end of an if statement.
  • considering that x(i) is always 0 why not assign directly the values to x(i) rather than adding them?