1

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[],]];
Paus
  • 11
  • 2

2 Answers2

3

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)
C. E.
  • 70,533
  • 6
  • 140
  • 264
1

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++]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148
  • 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