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.

There is a list with numbers 1 to 8 ( p1 ) and another list (j) which contains 4 numbers which shows different 4 positions of the elements in list p1. I want to take 4 elements from p1 related to the 4 numbers of positions from the list j and multiply those selected 4 numbers from list p1 by 2.

The code below is a function that do the procedure that I have mentioned above :

p1 = {1, 2, 3, 4, 5, 6, 7, 8};

DoMul[p1_] := Module[{nmu, e1, j, mul, Replacement},
j = {1, 6, 7, 8};
i = 1; While[i <= 4,
e1 = Extract[p1, {j[[i]]}];
mul = 2*e1;
Replacement = ReplacePart[p1, j[[i]] -> mul];    
; i++];
Replacement]; 

The problem is that I do not know how to update p1 in each iteration ( There are 4 iterations ) and the result will be :

{1, 2, 3, 4, 5, 6, 7, 16}

but the correct answer must be :

{2, 2, 3, 4, 5, 12, 14, 16}

Does anyone know how to update the p1 list in each iteration?

share|improve this question

3 Answers 3

up vote 2 down vote accepted
p1 = {1, 2, 3, 4, 5, 6, 7, 8};
j = {1, 6, 7, 8};

p1[[j]] *= 2;
p1

(* {2, 2, 3, 4, 5, 12, 14, 16} *)

Replacing your function (I assume you want to keep the argument/original unchanged and return the changed version):

p1 = {1, 2, 3, 4, 5, 6, 7, 8};

domul[p1_] := Module[{replacement = p1, j = {1, 6, 7, 8}},
   replacement[[j]] *= 2;
   replacement];

domul[p1]

(* {2, 2, 3, 4, 5, 12, 14, 16} *)

Also note I changed things to lowercase - bad idea in general to use uppercase initials, might clash with Mathematica built-in symbols.

share|improve this answer
    
@RunnyKine: LOL - grabbed a coffee, did not see yours. If you'd like this too-similar result deleted, no worries....and a +1 on yours for penance. –  rasher Apr 1 at 10:07
    
Lol. The more the merrier. –  RunnyKine Apr 1 at 10:17
    
@ rasher : I used it and it properly worked out of the function. But it doesn't work when I use it inside the function DoMul[p1_]. Could you please elaborate what the problem is ?! –  Shellp Apr 1 at 10:53
    
@Shellp: see update. Let me know if further clarification needed. –  rasher Apr 1 at 11:06
    
@ rasher : many thanks for it!! –  Shellp Apr 1 at 11:07

Just do the following:

p1[[j]] = 2 p1[[j]]

Then p1 gives:

{2, 2, 3, 4, 5, 12, 14, 16}
share|improve this answer

Redundant way :

Fold[MapAt[2 # &, #1, #2] &, p1, j]
share|improve this answer
    
@ esprit Thank you esprit!! It's a brilliant way !! –  Shellp Apr 1 at 11:06
1  
MapAt could also be used Fold-lessly here: MapAt[2 # &, p1, List /@ j] –  Aky Apr 1 at 11:50
    
@Aky : Yes, indeed! –  qwerty Apr 1 at 12:12

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.