5
$\begingroup$

Say I have the matrix

A = {{a,b,c,d,e}, {f,g,h,j,k}}

and I want to set some of these to zero. I have been doing this via

A/.{a->0, b->0}.

Is there a way to set a bunch to zero at once? I am dealing with many more parameters than 8 and would like to not type "->0," a million times. I tried

A/.{a,b,c}->0

But this just sets the list {a,b,c} to 0 (I believe). Thanks for the help.

$\endgroup$
2
  • $\begingroup$ Look up ReplacePart[]. But, you do not have a matrix, since your "rows" do not have the same dimensions. $\endgroup$ Jun 7, 2016 at 15:49
  • $\begingroup$ Whoops, thanks! $\endgroup$
    – user46348
    Jun 7, 2016 at 16:07

3 Answers 3

7
$\begingroup$

In terms of generating the replacement rule efficiently, you can do the following:

A = {{a, b, c, d, e}, {f, g, h, j}};    
A /. Thread[{a, b, c} -> 0]

(*{{0, 0, 0, d, e}, {f, g, h, j}}*)
$\endgroup$
2
  • $\begingroup$ Thanks a bunch! Will put to use immediately! $\endgroup$
    – user46348
    Jun 7, 2016 at 16:35
  • $\begingroup$ Great to hear, enjoy! $\endgroup$
    – Yves Klett
    Jun 7, 2016 at 17:30
7
$\begingroup$

Or you can use Map

A = {{a, b, c, d, e}, {f, g, h, j}};      
A /. (# -> 0 & /@ {a, b, c})

Update: or to have fun.

Fold[#1 /. #2 -> 0 &, A, {a, b, c}]
$\endgroup$
4
$\begingroup$

I would argue that the most idiomatic solution is

A /. a | b | c -> 0
$\endgroup$
1
  • 1
    $\begingroup$ Since he has a long list of parameters that will become zero.. A /. Alternatives @@ {a, b,c} -> 0 $\endgroup$
    – BlacKow
    Jun 7, 2016 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.