2

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

Karsten7
  • 27,448
  • 5
  • 73
  • 134
Min-Seok
  • 21
  • 1

2 Answers2

10
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]
Karsten7
  • 27,448
  • 5
  • 73
  • 134
4

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)$

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371