1
$\begingroup$

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?

$\endgroup$
3
$\begingroup$
m = 5;
sa = SparseArray[{{i_, j_} /; j == Min[2 i, m] :> 
    p, {i_, j_} /; j == 2 i - m :> q}, {m, m}]

enter image description here

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}]

enter image description here

$\endgroup$
0
$\begingroup$

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

enter image description here

$\endgroup$
0
$\begingroup$

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}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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