Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 8 down vote accepted

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
share|improve this answer
    
Tanks!!!I had not thought about the Sign. –  isa_vita Jan 5 '13 at 20:39
    
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. –  isa_vita Jan 5 '13 at 21:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.