3
$\begingroup$

Let list1 be a list of variables of the form {c1 a, c2 b, ...} where $a,b,...\in\mathbb{C}$ and $c1,c2,...\in\mathbb{Z}$. I am looking for a substitution rule to turn all the integers to 1 and just keep the variables in the list.

Example:

list1={3 a,4 b,-2 c,9 d};

Desired result:

list1/.Integers->1

{a,b,c,d}

Please, let me know if there is a function that can do this. Or maybe it can be implemented in a way such that it works fast? Currently I am using the following workaround:

temp2 = list1; temp3 = temp2 /.a->1/.b->1/.c->1/.d->1;
Do[
  temp2[[ii]] = temp2[[ii]]/temp3[[ii]];
, {ii, 1, Dimensions[temp2][[1]]}];

But it becomes rather slow once the length of list1 gets large (about 50 000 entries). Is there a way to speed things up?

$\endgroup$
5
$\begingroup$

The solution depends on how you want a zero integer coefficient treated.

list1 = {0 v, 3 a, 4 b, -2 c, 9 d};

Variables[list1]

{a, b, c, d}

list1 /. _Integer :> 1

{1, a, b, c, d}

list1 /. x_Integer :> Unitize[x]

{0, a, b, c, d}

$\endgroup$
  • 1
    $\begingroup$ Perfect! I just ran into an issue with zeros and your answer resolved the issues immediately. Thank you! $\endgroup$ – Kagaratsch Nov 25 '14 at 23:37
4
$\begingroup$

It looks like what you want is:

list1 /. {_Integer -> 1}
$\endgroup$
  • $\begingroup$ Ah, sniped me by a few seconds : ) $\endgroup$ – evanb Nov 25 '14 at 23:16
  • $\begingroup$ @evanb -- Your explanation is better than mine though! $\endgroup$ – bill s Nov 25 '14 at 23:25
4
$\begingroup$

You can use a pattern to just operate on the integers.

For example, list1 /. _Integer -> 1 yields {a,b,c,d}.

Not sure if it's as fast as you need it.

Explanation: the underscore _ is an unnamed pattern and the attached Integer says that the pattern should only match things whose Head is Integer. You can use other heads after the _, of course, to match different things...

$\endgroup$

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.