4
$\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$
  • $\begingroup$ Look up ReplacePart[]. But, you do not have a matrix, since your "rows" do not have the same dimensions. $\endgroup$ – J. M. will be back soon Jun 7 '16 at 15:49
  • $\begingroup$ Whoops, thanks! $\endgroup$ – user46348 Jun 7 '16 at 16:07
6
$\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$
  • $\begingroup$ Thanks a bunch! Will put to use immediately! $\endgroup$ – user46348 Jun 7 '16 at 16:35
  • $\begingroup$ Great to hear, enjoy! $\endgroup$ – Yves Klett Jun 7 '16 at 17:30
6
$\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$
3
$\begingroup$

I would argue that the most idiomatic solution is

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

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.