# Writing code to update a large matrix?

How can I write a code to update a matrix based on certain rules? I plan on constructing a large matrix, and I cannot submit entries one by one.

The rules for the matrix are as followed:

$$P(i,j)= \begin{cases} p, & \text{if j = 2i}\land m \\ q, & \text{if j = (2i-m) }\lor 0 \end{cases}$$

P is square. I was thinking of just defining it to be a 0 matrix first, then updating the values with whatever code. However, I can't seem to think of how that would be done. I've never heard of updating a matrix. For a given $m$, how would one generate such matrix in Mathematica? Could someone list an example?

## 3 Answers

m = 5;
sa = SparseArray[{{i_, j_} /; j == Min[2 i, m] :>
p, {i_, j_} /; j == 2 i - m :> q}, {m, m}] mat = Partition[Range[m^2], m];
sa2 = SparseArray[{{i_, j_} /; j == Min[2 i, m] :> p,
{i_, j_} /; j == 2 i - m, 0] :> q,
{i_, j_} :> mat[[i, j]]}, {m, m}];
Row[MatrixForm /@ {mat, sa2}] There's no need to update values; you can use Table and create it in one pass.

m = 4;
Table[
Which[
j == 2 i && j == m, p,
j == 2 i - m || j == 0, q,
True, 0
], {i, 10}, {j, 10}] // MatrixForm Updating an existing matrix

randomP = RandomInteger[{0, 9}, {5, 5}];

m = 2

ReplacePart[randomP, {{i_, j_} /; And[j == 2 i, j == m] -> p,
{i_, j_} /; Or[j == 2 i - m, j == 0] -> q}] 