# NxN diagonal matrix with mixed zero and nonzero diagonal elements

I'd like to make a function that takes an odd integer N and returns a diagonal matrix A with the odd diagonal elements $$A_{11}$$, $$A_{33}$$, etc. equal to zero and the even diagonal elements $$A_{22}$$, $$A_{44}$$, etc. equal to one. The best idea I've come up with is to use ReplacePart on a (NxN) constant array. I had hoped that the following would do the job:

A[N_]:= ReplacePart[ConstantArray[0,{N,N}],{2 i_,2 i_}->1]


but it seems like {2 i_,2 i_} is not a recognisable pattern (unlike if I were to put in {i_,i_} it would replace all diagonal elements with ones).

• Please do not use N as a variable. N is a built-in function in Mathematica. In general, avoid naming your own variables or functions using names that start with a capital letter. – C. E. Oct 2 '20 at 13:05
• Thanks for the tip! Will use n henceforth – igunnarsson Oct 2 '20 at 13:08

## 4 Answers

n = 9;
ReplacePart[ConstantArray[0, {n, n}], {i_?EvenQ, i_?EvenQ} -> 1]
% // MatrixForm


Or

Clear["*"];
n = 9;
M = SparseArray[{{i_, i_} /; Mod[i, 2] == 0 -> 1}, {n, n}];
M // Normal // MatrixForm

• Your SparseArray solution can be written more simply as SparseArray[{i_?EvenQ, i_} -> 1, n]. – C. E. Oct 2 '20 at 13:03
• @C.E. Thank you! – cvgmt Oct 2 '20 at 13:07

Another solution:

diagonalMatrix[n_] := DiagonalMatrix@PadRight[{}, n, {0, 1}]

Mod[DiagonalMatrix[Range[#] - 1], 2] & @ 7

Boole @ Array[EvenQ@# && # == #2 &, {#, #}] & @ 7

SparseArray[Band[{2, 2}, {#, #}, {2, 2}] -> 1] & @ 7

SparseArray[{i_, i_} :> Mod[i + 1, 2], {#, #}] & @ 7

MapAt[0 # &, IdentityMatrix@#, {;; , ;; ;; 2}] & @ 7

MapIndexed[Mod[#2[] + 1, 2] # &]@ IdentityMatrix[#] & @ 7

ReplacePart[IdentityMatrix@#, {i_, i_} :> Mod[i + 1, 2]] & @ 7


all give

% // MatrixForm // TeXForm


$$\left( \begin{array}{ccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$

This maybe easier to understand?

Table[Boole[OddQ@i && OddQ@j && i == j], {i, 0, 5}, {j, 0, 5}]
`