If-statements within a for loop does not respond to my counter appropriate?

1 view (last 30 days)
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 100x1. 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

Accepted Answer

Guillaume
Guillaume on 12 Oct 2017
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?
  1 Comment
Guillaume
Guillaume on 12 Oct 2017
And here is the way to do the same without loops:
x = zeros(100,1); %Preallocation
name1 = randi(30,100,1) %vector
name = randi(([0 1], 100,1) %vector
increments = [25000; 75000; 200000]; %needs to be column vector to match x being a column vector
condition = name & name1 >= 10;
startruns = strfind([0, condition.'], [0 1]); %transpose required because strfind only works on row vector
endruns = strfind(condition.', [1 0]); %same
if numel(startruns) > numel(endruns) %could be 1 more if condition ends with a run of 1s
startruns(end) = [];
end
x(endruns + 1) = x(endruns + 1) + increments(min(3, endruns - startruns + 1));

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 12 Oct 2017
val = [25000; 75000; 200000];
op0 = name1 >= 10 & name == 1;
x = zeros(size(name)+[1 0]);
a = diff([0;op0(:);0]);
n = accumarray(cumsum(a == 1).*[op0;false] + 1,1);
x(a == -1) = val(n(2:end));

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!