TransWikia.com

NxN diagonal matrix with mixed zero and nonzero diagonal elements

Mathematica Asked by igunnarsson on July 6, 2021

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

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

Correct answer by cvgmt on July 6, 2021

Another solution:

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

Answered by C. E. on July 6, 2021

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

Answered by kglr on July 6, 2021

This maybe easier to understand?

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

Answered by wuyudi on July 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP