2
$\begingroup$

I want to replace some elements in list.

Assume that we have

A={{1,2,3,4},
   {5,6,7,8},
   {9,10,11,12},
   {13,14,15,16}}

and we want to replace elements A[[i,j]] to 30 such that [i,j] is in {(2,2),(2,3),(3,2),(3,3)}

Then, the result is following:

B={{1,2,3,4},
   {5,30,30,8},
   {9,30,30,12},
   {13,14,15,16}}

We can do it using Replace but, as you know, it is very cumbersome and it is not a good idea if the list has large dimension.

If you have fancy method for this, please let me know.

Thanks

$\endgroup$
  • $\begingroup$ For large arrays you should have a look at SparseArray. $\endgroup$ – Karsten 7. Jul 25 '15 at 14:33
  • $\begingroup$ Related: (52385) $\endgroup$ – Mr.Wizard Jul 25 '15 at 19:30
10
$\begingroup$
a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}

ReplacePart can be used with explicit positions

b = ReplacePart[a, {{2, 2}, {2, 3}, {3, 2}, {3, 3}} -> 30]

or with positions matching a pattern

b = ReplacePart[a, {(2 | 3), (2 | 3)} -> 30]
{{1, 2, 3, 4}, 
 {5, 30, 30, 8}, 
 {9, 30, 30, 12}, 
 {13, 14, 15, 16}}

or

b = ReplacePart[a, {i_, j_} /; 1 < i < 4 && 1 < j < 4 -> 30]
$\endgroup$
4
$\begingroup$

The fastest way is usually an assignment on Part, and it generalizes well.
(See my comments in Elegant operations on matrix rows and columns.)

A = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};

B = A;
B[[2 ;; 3, 2 ;; 3]] = 30;
B // MatrixForm

$\left( \begin{array}{cccc} 1 & 2 & 3 & 4 \\ 5 & 30 & 30 & 8 \\ 9 & 30 & 30 & 12 \\ 13 & 14 & 15 & 16 \\ \end{array} \right)$

Less efficiently but cleanly you can also use MapAt is a slightly nonstandard way:

MapAt[30 &, A, {2 ;; 3, 2 ;; 3}] // MatrixForm

$\left( \begin{array}{cccc} 1 & 2 & 3 & 4 \\ 5 & 30 & 30 & 8 \\ 9 & 30 & 30 & 12 \\ 13 & 14 & 15 & 16 \\ \end{array} \right)$

$\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.