# Replacing specific parts of a matrix

I have lensp=101; pid=0.5212; qid=1-pid; e1=0;

Let's say I have a matrix such as newp = Table[e1, {i, lensp}, {j, lensp}];

I am trying to replace the elements of the matrix such that for each row i, the Min[i+1,lensp]th column=pid, and the Max[i-1,1]th column=1-pid. So each row should have two non-zero elements and the rest are zeros. [The Matlab code is newp(i,min(i+1,lensp))=pid and correspondingly]. I have tried many times in Mathematica but without success. I have tried

For[i = 1, i <= lensp, i++,
For[j = 1, j <= lensp, j++,
newp = ReplacePart[newp, newp[[i, Min[i + 1, lensp]]] = pid,
newp[[i, Max[i - 1, 1]] ] = qid]
]
]


but it does not work.

• Please properly format your question. As a not-so-novice user you should already be able to do that yourself. In case you don't know how, see here Dec 26, 2016 at 22:58
• Sorry about that. I would properly format my question when asking next time. Dec 26, 2016 at 23:49

Using lensp = 9,

newp1 = SparseArray[{{i_, j_} /; j == Min[i + 1, lensp] ->
pid, {i_, j_} /; j == Max[i - 1, 1] -> qid}, {lensp, lensp}];
newp1 // MatrixForm


or

newp2 = ReplacePart[newp, {{i_, j_} /; j == Min[i + 1, lensp] ->
pid, {i_, j_} /; j == Max[i - 1, 1] -> qid}];
newp2 // MatrixForm • Thank you very much. This definitely works. Dec 26, 2016 at 23:52

With a smaller matrix:

lensp = 11; pid = 0.5212; qid = 1 - pid; e1 = 0;
newp = Table[e1, {i, lensp}, {j, lensp}];


One can change the elements with a straightforward assignment newp[[i, j]] = new value:

Do[newp[[i, Min[i + 1, lensp]]] = pid, {i, lensp}];
Do[newp[[i, Max[i - 1, 1]]] = 1 - pid, {i, lensp}];

MatrixForm[newp] But seeing the form of the output, it's better to use SparseArray and Band to construct a matrix from scratch:

sa = SparseArray[{Band[{1, 2}] -> pid, Band[{2, 1}] -> 1 - pid,
{1, 1} -> 1 - pid, {lensp, lensp} -> 1 - pid}, {lensp, lensp}]

MatrixForm @ sa


the same as for newp

sa == newp


True

• Thank you very much. This definitely works. Dec 26, 2016 at 23:53