How to define a matrix with all elements 0?

9

1

A matrix can be defined as

M = Array[m, {3, 3}]

which gives

{{m[1, 1], m[1, 2], m[1, 3]}, {m[2, 1], m[2, 2], m[2, 3]}, {m[3, 1], m[3, 2], m[3, 3]}}

How to give all m[i, j] the value 0 (if M is a NxN matrix)?

R.Wigner

Posted 2014-05-11T09:57:14.907

Reputation: 883

Question was closed 2014-05-11T14:08:21.430

3ConstantArray[0,{3,3}], SparseArray[{},{3,3}]. m[[;;,;;]]=0. – Kuba – 2014-05-11T10:00:32.623

2And Array[0 &, {3, 3}] – Öskå – 2014-05-11T10:01:12.787

2Expanding on Oska's comment, if you simply define m[i_,j_]=0, then you'll get the array you want, since Array produces an array with elements m[i,j]. Oska did essentially this using a pure function. – Mark McClure – 2014-05-11T12:28:28.280

2Also: 0 BoxMatrix[1] – Mr.Wizard – 2014-05-11T14:15:36.307

Answers

7

Summarizing what has been said in the comments.

You can create a zero matrix by many ways:

ClearAll[n, m1, m2, m3, m4, m5, m6, m7, m8, m9, size]
size[n_] := {n, n}
n = 3;
m1 = ConstantArray[0, size[n]];
m2 = SparseArray[{}, size[n]];
m3 = Module[{mm = Array[m, size[n]]}, mm[[;; , ;;]] = 0; mm];
m4 = Module[{m}, m[i_, j_] = 0; Array[m, size[n]]];
m5 = 0 Array[,size[n]];
m6 = Array[0 &, size[n]];
m7 = Table[0, {#}, {#2}] & @@ size[n];
m8 = ArrayReshape[{0}, size[n]];
m9 = 0*BoxMatrix@1

m1 == m2 == m3 == m4 == m5 == m6 == m7 == m8 == m9
True

With a speed priority given to SparseArray[{}, size[n]].

m1 // MatrixForm

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

Öskå

Posted 2014-05-11T09:57:14.907

Reputation: 8 267