2

Please I need help on how to replace elements in a matrix with another elements. For example, I have a (5,5) matrix, and I like to replace elements from All rows and column 3 to 5, with zero. such that (All, 3;;5) replace with zero.

m = MatrixForm[Partition[Range[25]^2, 5]]

Sample Matrix

I like to replace all the elements in the specified area with zero: enter image description here

Geop
  • 87
  • 3

2 Answers2

4

Don't use MatrixForm when defining the matrix. It's only a display wrapper, as explained here.

m = Partition[Range[25]^2, 5]

{{1, 4, 9, 16, 25}, {36, 49, 64, 81, 100}, {121, 144, 169, 196, 225}, {256, 289, 324, 361, 400}, {441, 484, 529, 576, 625}}

Replacement:

m[[All, 3 ;; 5]] = 0;
m

{{1, 4, 0, 0, 0}, {36, 49, 0, 0, 0}, {121, 144, 0, 0, 0}, {256, 289, 0, 0, 0}, {441, 484, 0, 0, 0}}

Roman
  • 47,322
  • 2
  • 55
  • 121
2
m = Partition[Range[25]^2, 5]

A few more alternatives:

SparseArray[m[[All,  ;; 2]], Dimensions[m]]
PadRight[m[[All, ;; 2]], Dimensions@m]
MapAt[0 &, m , {All, 3 ;; }]

all give

{{1, 4, 0, 0, 0}, {36, 49, 0, 0, 0}, {121, 144, 0, 0, 0}, {256, 289, 0, 0, 0}, {441, 484, 0, 0, 0}}

kglr
  • 394,356
  • 18
  • 477
  • 896