List manipulation - End loop

Given are two matrices (a & b). I want to end the For-loop if all values in the matrix (a minus b) are smaller than 7, in contrast to any value in the matrix (a minus b) is smaller than 7. Can anybody help me with this problem?

For[Q = 0, Q <= 20, Q += 1,
Print[Q];
Print[a = {{40, 40, 40}, {40, 40, 40}, {40, 40, 40}}];
Print[b = Q {{4, 4, 4}, {4, 3, 4}, {4, 4, 4}}];

compare[matrix_, length_, width_, value_] :=
Module[{state}, state = False; For[i = 1, i <= length, i++,
For[j = 1, j <= width, j++,
If[matrix[[i, j]] < value, state = True]]]; Return[state]];

If[compare[a - b, 3, 3, 7], Break[],]];
• Perhaps Max[a - b] < 7 – Simon Woods Aug 27 '13 at 18:46
• Related: (8650) – Mr.Wizard Aug 28 '13 at 10:47

For example:

compare[a_, b_] := And @@ (Less[#, 7] & /@ Flatten@(a - b))

Then

For[Q = 0, Q <= 20, Q += 1, Print[Q];
Print[a = {{40, 40, 40}, {40, 40, 40}, {40, 40, 40}}];
Print[b = Q {{4, 4, 4}, {4, 3, 4}, {4, 4, 4}}];
If[compare[a, b], Break[]]]

Stops at Q=12:

{{40,40,40},{40,40,40},{40,40,40}}

{{48,48,48},{48,36,48},{48,48,48}}

Alternative that may or may not be faster (other members are much, much better at optimizing for speed, if you have this problem you should say so):

compare2[a_, b_] := ! Or @@ Positive@UnitStep@Flatten@(a - b - 7)
• Replace 7 with 0.001? :P – C. E. Aug 28 '13 at 11:22
• Also see the comment by Simon Woods, which is a simpler and faster test. – C. E. Aug 28 '13 at 11:25
• Thanks. Now I want to end the For-loop if the difference between A and B at every point in the matrix is less than 0.001(Aij-Bij). How can I fix this? – Paus Aug 28 '13 at 11:27
• ij is given I suppose? Replace 7 with 0.001(A[[i,j]]-B[[i,j]]) – C. E. Aug 28 '13 at 11:30

If the purpose is to print only the matrices that comply with the constraint (as the last printed are the first exception), perhaps (using the compare function of Anon):

compare[a_, b_] := And @@ (Less[#, 7] & /@ Flatten@(a - b));
a = {{40, 40, 40}, {40, 40, 40}, {40, 40, 40}};
b = {{4, 4, 4}, {4, 3, 4}, {4, 4, 4}};
Q = 0;
While[compare[a, Q b] == False, Print[Q]; Print[a]; Print[Q b]; Q++]
• Of course you could just change the comparison test to the beginning of the sequence of commands. – ubpdqn Aug 28 '13 at 10:48
• Or put Print inside the If. (I don't see how putting it in the beginning would solve it.) – C. E. Aug 28 '13 at 10:56
• @Anon thank you and sorry, yes it would only work if a and b, Q ( hence Qb) were defined outside the loops and the first statement was the comparison, then it would break once test was true and before printing but as structured I am in error. – ubpdqn Aug 28 '13 at 11:07