5
$\begingroup$

I have a very large n x n matrix from which I want to take a row i from and substitute every element with 0. When I try the below command however, the ith row is not replaced by a list of n zeros but a single zero, which breaks the matrix.

ReplacePart[A, {i -> {0}}]

Is there a neat way of substituting that {0} with some command that produces an automatic list of (length[A]) number of 0s?

$\endgroup$
2
  • $\begingroup$ For in place modification (no copy), maybe A[[4,All]]*=0 $\endgroup$
    – user1066
    Jan 15 at 15:53
  • 2
    $\begingroup$ Another possibility is to use Dot, e.g. DiagonalMatrix[1 - UnitVector[Length[A], i]].A $\endgroup$
    – Carl Woll
    Jan 15 at 16:03
10
$\begingroup$
A = Array[a, {10, 10}];

i = 4;
b = ReplacePart[A, {i, _} -> 0];

b // MatrixForm

enter image description here

You can also do

c = A; c[[i, ;;]] = 0;

d = MapAt[0 & /@ # &, A, {i}];

e = MapAt[0 &, A, {i, All}];

b == c == d == e
True
$\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.