2
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ _ has special meaning in Mathematica, and is not intended for names of variables. $\endgroup$ – J. M. will be back soon Apr 1 '17 at 1:17
1
$\begingroup$
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}}}

$\endgroup$
0
$\begingroup$

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]}]
$\endgroup$
0
$\begingroup$
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}}} *)
$\endgroup$
  • $\begingroup$ @Aran please see this answer $\endgroup$ – Ali Hashmi Apr 1 '17 at 3:34

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.