There are similar questions to this on the forum but none fit the purpose here:
I would like to extract certain elements of a matrix depending on whether a factor is present or not, and create another matrix of the same size with those elements and zeros everywhere else. For example, given
\begin{equation} \left [ \begin{array}{c c} a x & b x^2 \\ c y & d y^2 \end{array} \right ] \end{equation}
I would like to create a new matrix with just the elements that have $x^2$ as a member and zeros everywhere else.
\begin{equation} \left [ \begin{array}{c c} 0 & b x^2 \\ 0 & 0 \end{array} \right ] \end{equation}
I've tried variants of things like this but can't get it to work
SIGMA = {{ a x , b x^2},{c y , d y^2}};
SIGMAx2 = Select[SIGMA , MemberQ[#, x^2] &];
HoldPattern. Please let me know if it isn't) – Pinguin Dirk Sep 18 '13 at 14:07TimesisOrderless, therefore you don't need two blanks. This in turn allows to ditchHoldPattern, so that you could just use:Replace[SIGMA, Except[___ x^2 ] -> 0, {2}]. – Leonid Shifrin Sep 18 '13 at 14:40Orderless) which screwed things up (I looked atTraceand couldn't make sense of it). IntroducingHoldPatternsolved it then (with the 2 blanks) (hence my first commend above). Thanks for pointing that out, @LeonidShifrin – Pinguin Dirk Sep 18 '13 at 14:45{MatchQ[ x^2 c y, HoldPattern[___ x^2 ___]], MatchQ[ x^2 c y, ___ x^2 ___], MatchQ[ x^2 c y, a___ x^2 b___]}, and couldn't properly make sense of it (2nd vs 3rd), but now it makes sense (looking atTrace). And asExceptdoesn't allow named patterns, I chose to useHoldPattern. – Pinguin Dirk Sep 18 '13 at 14:54Replace[m, a_ /; FreeQ[a, x^2] -> 0, {2}]– ssch Sep 18 '13 at 15:46