5
$\begingroup$

I have list of objects:

 list = {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}, {13, 13, 0.05, 0.05}};

 list = {{x,y,Vx,Vy},{x,y,Vx,Vy},...};

And

object = {10, 10};

I want when I change position of object the objects from the list to follow the first object.

I try with this:

If[object[[1]] < #1 && #3 > 0, list = {#1,#2,-#3 ,#4}, list = {#1,#2,#3,#4}] &@@@list
If[object[[1]] > #1 && #3 < 0, list = {#1,#2,-#3 ,#4}, list = {#1,#2,#3,#4}] &@@@list
If[object[[2]] < #1 && #4 > 0, list = {#1,#2,#3 ,-#4}, list = {#1,#2,#3,#4}] &@@@list
If[object[[2]] < #1 && #4 < 0, list = {#1,#2,#3 ,-#4}, list = {#1,#2,#3,#4}] &@@@list

and works but only the first cycle. I know that I can do this with:

If[object[[1]] < list[[1, 1]] && list[[1, 3]] > 0, list[[1, 3]] *= -1]....

But is very slow and not look nice :). And doesn't work completely correct.

$\endgroup$
8
$\begingroup$

Perhaps:

list = list /. {x_, y_, vx_, vy_} ->
          {x, y, Sign[#[[1]] - x] vx, Sign[#[[2]] - y] vy}& @ object

Edit

There is however a small subtlety: if your list is composed by exactly four sublists, the pattern {x_, y_, vx_, vy_} will match the whole list of lists. So, for avoiding this edge case, a good practice is to use pattern tests. I will write the four of them, but in your case one will suffice

list /. {x_?NumericQ, y_?NumericQ, vx_?NumericQ, vy_?NumericQ} ->
                          {x, y, Sign[#[[1]] - x] vx, Sign[#[[2]] - y] vy} &@ object
$\endgroup$
  • $\begingroup$ Tanks!!!I had not thought about the Sign. $\endgroup$ – isa_vita Jan 5 '13 at 20:39
  • $\begingroup$ I made little change because the sign of the velocity changed every cycle. I swapped Sign[#[[1]] - x] with If[(#[[1]] < x && vx > 0) || (#[[1]] > x && vx < 0), -1, 1] and works great. $\endgroup$ – isa_vita Jan 5 '13 at 21:14

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.