3
$\begingroup$

I have a list {{x1,y1},{x2,y2}...} a list {z1,z2...}, I want to create a new list {{x1,w1},{x2,w2}...}, where wi=0.5 if yi<zi and wi=-0.5 otherwise. I attack this problem by the following code. However, how to avoid creating a new list lsNew? I think it is a redundancy.

ls = {{1, 2}, {2, 3}, {1, 5}};
v = {2, 7, 8};
lsNew = Transpose[Insert[Transpose[ls], v, 3]]
lsWanted={#[[1]], If[#[[2]] < #[[3]], 0.5, -0.5]} & /@ lsNew
$\endgroup$
1
  • $\begingroup$ no, i just want to compare v and ls directly using a pure function... I dont't know if there is a way to do this $\endgroup$ Dec 30, 2015 at 2:31

6 Answers 6

5
$\begingroup$

Same idea as @eldo with a simpler MapThread:

MapThread[{#1[[1]], If[#1[[2]] < #2, 0.5, -0.5]} &, {ls, v}]
$\endgroup$
2
  • $\begingroup$ This is what I want, because this doesn't create a new list, but directly compare them. $\endgroup$ Dec 30, 2015 at 3:37
  • $\begingroup$ @buzhidao This is one of those questions that will produce quite a few answers. There will probably be some much more interesting ones to come. $\endgroup$
    – kale
    Dec 30, 2015 at 3:39
3
$\begingroup$
{#[[1]], If[#[[2]] < #[[3]], 0.5, -0.5]} & /@ MapThread[Append, {ls, v}]

{{1, -0.5}, {2, 0.5}, {1, 0.5}}

This should be very fast:

ls[[All, 2]] = Unitize[Last /@ ls - v] - 0.5

ls

{{1, -0.5}, {2, 0.5}, {1, 0.5}}

$\endgroup$
2
$\begingroup$
{#[[1]], 0.5 - UnitStep[#[[2]] - v]}\[Transpose] &[ls\[Transpose]]
$\endgroup$
2
$\begingroup$
MapAt[If[# < 0, 0.5, -0.5] &, ls - Map[{0, #} &, v], {All, 2}]
$\endgroup$
2
$\begingroup$

Since you do not want to make new lists, and looking for something different to the other answers:

ls[[All, 2]] = Transpose[{ls[[All, 2]], v}] /. {{x_, y_} /; x < y :>0.5, {_, _} -> -0.5}
ls
$\endgroup$
2
$\begingroup$

In the spirit of @MikeHoneychurch, without If:

Thread[{#1[[All, 1]], Thread[#1[[All, 2]] < #2]}] &[ls, v] /. {True :> 0.5, False :> -0.5}
$\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.