MATLAB: If statement of type cell problem..

charifstatement

It seems an easy problem but I just can't figure it out.
let A,B,C be vectors.
for i=1:100
if A(i)<B(i)
C(i)=0;
else
C(i)=1;
end
end
this code, of course, works well. but if I define, say D={A(i)<B(i)} and
for i=1:100
if D{1}==1
C(i)=0;
else
C(i)=1;
end
end
This code does not work. Looks like some kind of data type problem, but I just don't know how to fix it. Thanks in advance.

Best Answer

Check out the condition in the second block of code
if D{1}==1
At each iteration, the code is comparing the first element of the cell array D with 1 when it should be considering each element of D. But I suspect that won't work either because of the way that D was initialized.
What is the code for that initialization? Was it simply
D = {A<B}
which is different from (but similar to) your example of D={A(i)<B(i)}. In the case of D = {A<B}, D is just a single element cell array with the first element being a logical vector of dimension mx1 (where m is the length of the vectors A and B). So accessing
D{1}
returns a mx1 logical array which can't be compared to the single digit one.
What you want to do instead is initialize D as follows
D = A<B;
which will be a mx1 array/vector of logical elements where a 1 in the ith position indicates that A(i)<B(i) and a zero indicates the opposite.
Your second block of code then becomes
D = A<B;
for k=1:100
if D(k)==1
C(k)=0;
else
C(k)=1;
end
end
Try the above and see what happens!