"Cun Kang" wrote in message <jhla1v$805$1@newscl01ah.mathworks.com>...
> Below is my code which would not work.
> X =unifrnd(0,1,1,100);
> i=0;
> while(i<m<max(size(X)))
> if (X(1,i)<=0.2)
> X(1,i)= 1;
> else X(1,i)=0;
> i=i+1;
> end
         
Of course you should use Matt's method  there is no need for a programmed loop in this problem. Nevertheless it is important to understand what the difficulties are in your code so you won't repeat them in cases where a loop is actually needed. I see at least four main problems.
First, you wrote an inequality in the form "a<b<c" as the 'while' condition. Undoubtedly you intended it to mean "a is less than b and b is less than c". However that is *not* matlab's interpretation. It interprets a<b<c to mean (a<b)<c and first determines whether a<b is true or false. Then since that result is to be used in a second inequality with c, the truth value is converted to the numeric values 1 or 0, respectively. Finally it asks whether the numeric 1 or 0 is less than c. The answer to this is given by matlab as the result! That is worlds away from the above assumption. You should always use "(a<b)&(b<c)" and never "a<b<c" to avoid such a catastrophe.
The next fault I have with the code is that the first time it encounters a case where "X(1,i)<=0.2" holds true, it will then loop endlessly, never stopping, because you haven't incremented the 'i' index in that case. You placed the "i=i+1;" line in the wrong place. This is probably related to the fact that you have one too few 'end's in the whileloop.
Thirdly it is not necessary to use a 'while' instruction in your case because you know in advance how many times it is to repeat itself, so a 'for' instruction is much preferable.
The fourth problem is that you started things off with i equal to 0 and that is not a valid number to use as an index into X. You may have gotten an error message about this at the very beginning (which saved you from falling into an infinite loop.)
Roger Stafford
