# For loop inside an if condition statement

Is it possible to add a loop inside an if condition? I would like to achieve this

``````n = 3;
A = rand(0:10, n);
B = rand(0:10, 10, n);
C = rand(0:10, n);
flag = 0;

for i in 1:n
if A[i] == B[C[i], i]
flag = 1;
else
flag = 0;
break;
end
end
``````

in a more compact notation. Something like

``````n = 3;
A = rand(0:10, n);
B = rand(0:10, 10, n);
C = rand(0:10, n);
flag = 0;

if A[i] == B[C[i], i] for i in 1:n
flag = 1;
end
``````

I donâ€™t really understand your code, which breaks the loop unconditionally after the first iteration, but possibly youâ€™re looking for something like this, using a generator expression:

``````flag = any(A[i] == B[C[i], i] for i in 1:n)
``````
1 Like

Sorry, there was an else missing: Iâ€™ve edited my code. Thanks for your help, your suggestion seems to work!

With your modified code it would rather be

``````flag = all(A[i] == B[C[i], i] for i in 1:n)
``````

but you know better what you really want.

3 Likes

Yes, â€śall()â€ť is what I was looking for. Thanks again.