# Setting some Rows and Entries in a Matrix to 0

How can I set certain entries in a matrix to be 0?

Given an $m\times n$ matrix with specified values:

mat = Table[1/i, {i, n}, {j, m}]


I want to make some entries 0: I will replace row $i$ with zeros when the greatest prime factor of $i$ exceeds the greatest prime factor of $n$:

GreatestPrimeFactor := 1
GreatestPrimeFactor[n_Integer?Positive] := FactorInteger[n][[-1, 1]]
ReplacePart[m, {i_,j_}/; GreatestPrimeFactor[i]>GreatestPrimeFactor[n]-
>0]


I also want to set additional entries to 0, but before I do that, I want to record something to recall later; e.g., the column sums.

Total[mat, {1}]


Then I also set the $(i,j)$ entry to be $0$ when $j/\gcd(i,j)$ is composite:

 ReplacePart[m, {i_,j_}/;compositeQ[j/GCD[i,j]]->0]


How can this be done in the table environment? I will consider using Array instead of Table.

condition[i_, j_, n_] := FactorInteger[i][[-1, 1]] <= FactorInteger[n][[-1, 1]] &&
(j/GCD[i, j] == 1 || PrimeQ[j/GCD[i, j]])


Using SparseArray:

sa[m_, n_] := SparseArray[{{i_, j_} /; condition[i, j, n] -> 1/i}, {m, n}]


Example:

sa[10, 10] // MatrixForm // TeXForm


$\left( \begin{array}{cccccccccc} 1 & 1 & 1 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & 0 & 0 & \frac{1}{2} \\ \frac{1}{3} & \frac{1}{3} & \frac{1}{3} & 0 & \frac{1}{3} & \frac{1}{3} & \frac{1}{3} & 0 & \frac{1}{3} & 0 \\ \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4} & 0 & \frac{1}{4} \\ \frac{1}{5} & \frac{1}{5} & \frac{1}{5} & 0 & \frac{1}{5} & 0 & \frac{1}{5} & 0 & 0 & \frac{1}{5} \\ \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & \frac{1}{6} & 0 & \frac{1}{6} & \frac{1}{6} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & \frac{1}{8} & 0 & \frac{1}{8} \\ \frac{1}{9} & \frac{1}{9} & \frac{1}{9} & 0 & \frac{1}{9} & \frac{1}{9} & \frac{1}{9} & 0 & \frac{1}{9} & 0 \\ \frac{1}{10} & \frac{1}{10} & \frac{1}{10} & \frac{1}{10} & \frac{1}{10} & \frac{1}{10} & \frac{1}{10} & 0 & 0 & \frac{1}{10} \\ \end{array} \right)$

Using Table:

table[m_, n_] := Table[If[condition[i, j, n], 1/i, 0], {i, n}, {j, m}]

Normal[sa[10, 10]] == table[10, 10]


True

• @TheSubstitute, i think it is fixed now (replacing || with && in condition) – kglr Oct 8 '17 at 21:36
• Thanks. Why are there zeros in column 1? Can we avoid calling 1 a composite in the code? – The Substitute Oct 8 '17 at 21:39
• @TheSubstitute, changed condition to fix that issue. – kglr Oct 8 '17 at 21:45