2
$\begingroup$

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

$\endgroup$
4
$\begingroup$

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}}

$\endgroup$
2
$\begingroup$
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}}

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