1
$\begingroup$

Suppose I have a sequence a,b,c,d,e,f,g and for given sequence whose element is expressed as a1,a2,a3, ... , c1,c2,c3, ... g1,g2,g3, and so on.

And suppose from these sequence with some manipulation I have the following input

input = a1a2b1b2c2c3 + 100a1b2 + a1c2b2d3 + a1a2 + a3c1c2 + a3c1

Then I want to make a function that makes my specific variable be nonzero and all other variable be zero.

I want a function whose input is three variables such that only input variables are nonzero and others are zero

f[input, x3, y3] =  input/.->{x1->0, x2->0, x4->0, .... , y1->0, y2->0, y4->0, .... ] 

For example, f[input, a1,a2] = a1a2, and f[input, a1,b2]=100a1b2 and so on.

Are there any smart ways to implement this?

For some simple case I just did by my hand, i.e.,

inputa1a2=input/.{a3->0, b1->0, b2->0, c1->0, c2->0 c3->0} 

But for many variables, I realized this is inefficient and there seems to be a nice way


$\endgroup$

2 Answers 2

1
$\begingroup$
input = a1 a2 b1 b2 c2 c3 + 100 a1 b2 + a1 c2 b2 d3 + a1 a2 + a3 c1 c2 + a3 c1;

1. ReplaceAll + Alternatives + Complement + Variables:

ClearAll[f1]
f1 = # /. Alternatives @@ Complement[Variables @ #, {##2}] -> 0 &;

Examples:

f1[input, a1, a2]
a1 a2
f1[input, a1, b2]
100 a1 b2
f1[input, a3, c1, c2]
a3 c1 + a3 c1 c2

2. ReplaceAll + Alternatives + Variables:

ClearAll[f2]
f2 = # /. {a : Alternatives @@ {##2} -> a, Alternatives @@ Variables[#] -> 0} &;

Examples:

f2[input, a1, a2]
a1 a2
f2[input, a1, b2]
100 a1 b2
f2[input, a3, c1, c2]
a3 c1 + a3 c1 c2

3. Select + FreeQ + Alternatives + Complement + Variables:

ClearAll[f3]
f3 = Select[FreeQ[Alternatives @@ Complement[Variables  @#, {##2}]]] @ # &;

Examples:

f3[input, a1, a2]
a1 a2
f3[input, a1, b2]
100 a1 b2
f3[input, a3, c1, c2]
a3 c1 + a3 c1 c2
$\endgroup$
1
$\begingroup$

You may use Variables with DeleteCases.

With

input = a1 a2 b1 b2 c2 c3 + 100 a1 b2 + a1 c2 b2 d3 + a1 a2 + a3 c1 c2 + a3 c1;

Then

f[expr_, vars__] :=
 expr /. DeleteCases[Thread[Variables[expr] -> 0], Alternatives @@ {vars} -> 0]

and

f[input, a1, a2]
a1 a2
f[input, a1, b2]

100 a1 b2

f[input, a3, c1, c2]

a3 c1 + a3 c1 c2

Hope this helps.

$\endgroup$

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.