Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to generate all posible matrices with some conditions on the elements?

I need to make for given $n$ all $n\times n$ matrices $A=(a_{ij})$ with three conditions:

I. $a_{ij}=+1$ or $0$ or $-1$.

II. $a_{ij}=-a_{ji}$

III. if $a_{ij}\geq 0$ and $a_{jk}\geq 0$, then $a_{ik}\geq 0$; and $a_{ik}=0$ only if $a_{ij}=a_{jk}=0$

The only way I see is to expand these three conditions to equivalent but more elementary eight IF/ELSE conditions:

1) if $a_{ij}=+1$, then $a_{ji}=-1$

2) if $a_{ij}=+1$ and $a_{jk}=+1$, then $a_{ik}=+1$

3) $a_{ii}=0$

4) if $a_{ij}=0$, then $a_{ji}=0$

5) if $a_{ij}=0$ and $a_{jk}=0$, then $a_{ik}=0$

6) if $a_{ij}=+1$ and $a_{jk}=0$, then $a_{ik}=+1$

7) if $a_{ij}=0$ and $a_{jk}=+1$, then $a_{ik}=+1$

8) $a_{ij}=+1$ or $0$ or $-1$

And to generate for given $n$ all possible matrices, make it antisymmetric, then make all permutates of $+1$, $0$, $-1$; and after that deleting unnecessary cases with help of cycles. But it quickly became too complicated. Is there any more natural way?

PS this problem arised from this SE question and appeals to this book.

share|improve this question
I think you may have formulated conditions stronger than what you actually want. Your second one implies all diagonal entries are zero. Your third, taking k=i, then implies all off-diagonal entries are zero. Possibly that one is to be restricted to {i,j,k} all pairwise distinct? – Daniel Lichtblau Nov 27 '13 at 22:58
@DanielLichtblau III. can be explained detailed by 2), 5), 6), 7). – aeiklmkv Nov 27 '13 at 23:15
Maybe. But not in a way that I follow. – Daniel Lichtblau Nov 27 '13 at 23:40
Excuse me. If I understand your question, you are right that pairwise are distinct. In fact, indexes denote different objects. – aeiklmkv Nov 27 '13 at 23:52
Thanks for the clarification. A possible approach would be with dynamic programming. Start with only zeros on the main diagonal. Try a value in the 1,2 position. compute all other entries that the new one forces to take a specific value, and proceed in that way. Every time you reach a dead end or a new viable matrix, backtrack to the last new non-forced entry (deleting all values that were forced by its prior value), change it to a new value, continue. This is a sketchy outline but it might give a reasonably efficient way to generate all possibilites. – Daniel Lichtblau Nov 29 '13 at 20:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.