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 a list:

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

and I want to do this change

Replace[#[[1]], #[[1]] -> (#[[1]] + #[[3]])]& /@ list    
Replace[#[[2]], #[[2]] -> (#[[2]] + #[[4]])]& /@ list 

The problem is that the initial list doesn't change.

My list represents $\{\{x, y, v_x, v_y\}, \{x, y, v_x, v_y\}\} $ and I want to use a replacement rule to change the position of the objects and thereby represent movement.

share|improve this question
add comment

2 Answers

I'd recommend to apply certain function (here you'd like {#1 + #3, #2 + #4, #3, #4} &) at the level 1 of the list ( f @@@ list is a shorthand for Apply[ f, list, {1}]). So here a good way is :

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

list = {#1 + #3, #2 + #4, #3, #4} & @@@ list
{{1.05, 1.05, 0.05, 0.05}, {2.05, 2.05, 0.05, 0.05}}

If you want to play with ReplaceAll you can try another approach, e.g. this :

list = list /. {a_, b_, c_, d_} -> {a + c, b + d, c, d}

it yields the same list :

(list /. {a_, b_, c_, d_} -> {a + c, b + d, c, d}) == ({#1 + #3, #2 + #4, #3, #4} & @@@ list)
True
share|improve this answer
add comment

I think the problem is that you may have misunderstood the meaning of Replace. It doesn't replace anything in the sense of modifying the object on which it acts. It produces a new object. So what you really want to do if you want list to change is this:

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

(* ==> {{1, 1, 0.05, 0.05}, {2, 2, 0.05, 0.05}} *)

list = {#[[1]] + #[[3]], #[[2]] + #[[4]], #[[3]], #[[4]]} & /@
   list

(* ==> {{1.05, 1.05, 0.05, 0.05}, {2.05, 2.05, 0.05, 0.05}} *)

Then you can repeatedly apply the last assignment to represent the movement in the first two components.

Here I have explicitly assigned the result of the Map operation on list back to the variable list itself by using Set (list = ...).

share|improve this answer
add comment

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.