# Replacing an element of a list with constant depending on whether the element contains a certain expression

If there are any of the terms from the following list $x_1, x_2,...,x_n, y_1,...,y_m$ in a list, such as

   list = {{1,2,3,x1, x2^2},{4,5,6,y1}}


I want to be able to replace that term with a constant with coefficients indicating at what point in the list the term was replaced, so in the above example I would want

    {{1,2,3,c{1,4},c{1,5}},{4,5,6,c{2,4}}}


I've thought of using the following

Replaceif = {x1, x2, y1}
MemberQ[list,#]&/@Replaceif


with the Replace function, but it doesn't seem to use give an appropriate argument.

• _ has special meaning in Mathematica, and is not intended for names of variables. – J. M. will be back soon Apr 1 '17 at 1:17

vars = Alternatives @@ {x1, x2, x3, y1, y2, y3};
f =  MapIndexed[If[FreeQ[#, vars], #, Defer[c #2]] &, #, {2}] &;

f@list


{{1, 2, 3, c {1, 4}, c {1, 5}}, {4, 5, 6, c {2, 4}}}

How many terms do you have to change?

here is a start..

list = {{1, 2, 3, x1, x2^2}, {4, 5, 6, y1}};
rep[p_, r_] := Position[list, p] -> {"c"} Flatten@r;
t1 = Position[list, x1];
t2 = Position[list, x2^2];
t3 = Position[list, y1];
ReplacePart[list, {rep[x1, t1], rep[x2^2, t2], rep[y1, t3]}]

list = {{1, 2, 3, x1, x2^2}, {4, 5, 6, y1}}

pos = Position[list, Alternatives @@ Cases[list, _Symbol, Infinity]]
(* {{1, 4}, {1, 5, 1}, {2, 4}} *)

replace = (# -> HoldForm[c #]) & /@ pos[[All, 1 ;; 2]]
(* {{1, 4} -> c {1, 4}, {1, 5} -> c {1, 5}, {2, 4} ->
c {2, 4}} *)

ReplacePart[list, replace]
(* {{1, 2, 3, c {1, 4}, c {1, 5}}, {4, 5, 6, c {2, 4}}} *)

• @Aran please see this answer – Ali Hashmi Apr 1 '17 at 3:34