5
$\begingroup$

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).

$\endgroup$
2
  • 1
    $\begingroup$ 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. $\endgroup$
    – C. E.
    Oct 2, 2020 at 13:05
  • $\begingroup$ Thanks for the tip! Will use n henceforth $\endgroup$ Oct 2, 2020 at 13:08

4 Answers 4

6
$\begingroup$
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
$\endgroup$
2
  • 2
    $\begingroup$ Your SparseArray solution can be written more simply as SparseArray[{i_?EvenQ, i_} -> 1, n]. $\endgroup$
    – C. E.
    Oct 2, 2020 at 13:03
  • $\begingroup$ @C.E. Thank you! $\endgroup$
    – cvgmt
    Oct 2, 2020 at 13:07
6
$\begingroup$

Another solution:

diagonalMatrix[n_] := DiagonalMatrix@PadRight[{}, n, {0, 1}]
$\endgroup$
0
5
$\begingroup$
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]] + 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)$

$\endgroup$
2
$\begingroup$

This maybe easier to understand?

Table[Boole[OddQ@i && OddQ@j && i == j], {i, 0, 5}, {j, 0, 5}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.