2
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – Sascha Dec 26 '16 at 22:58
  • $\begingroup$ Sorry about that. I would properly format my question when asking next time. $\endgroup$ – Supratim Das Gupta Dec 26 '16 at 23:49
2
$\begingroup$

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

Mathematica graphics

$\endgroup$
  • $\begingroup$ Thank you very much. This definitely works. $\endgroup$ – Supratim Das Gupta Dec 26 '16 at 23:52
2
$\begingroup$

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]

enter image description here

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

$\endgroup$
  • $\begingroup$ Thank you very much. This definitely works. $\endgroup$ – Supratim Das Gupta Dec 26 '16 at 23:53
  • $\begingroup$ I would use Do instead of Table, since you aren't using the output. $\endgroup$ – march Dec 27 '16 at 1:17

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.