4
$\begingroup$

I have a list a = {0, 0, 0, 0, 0}; and now I would like to make only those elements 100 at the positions in pu = {1,4,5}; So I would like to get {100,0,0,100,100} ReplacePart[a, pu -> 100], doesn't show the right result unfortunately. Could anybody help me to solve this?

Thank you in advance! Carlijn Bakker

$\endgroup$
1
  • 1
    $\begingroup$ Try with Thread[pu -> 100] or Transpose[{pu}] -> 100. $\endgroup$ Dec 16, 2016 at 9:30

4 Answers 4

5
$\begingroup$

You can also use lists with Part or [[ ]]

a = {0, 0, 0, 0, 0};
a[[{1, 3}]] = 7;
a
pu = {1, 4, 5};
a[[pu]] = 100;
a

{7, 0, 7, 0, 0}

{100, 0, 7, 100, 100}

$\endgroup$
3
  • $\begingroup$ Thank you so much for the solution and the quick respons!! $\endgroup$ Dec 16, 2016 at 9:56
  • $\begingroup$ No worries :D Since you are new, dont forget to accept an answer if it solved your problem, that is useful for every body. $\endgroup$ Dec 16, 2016 at 9:58
  • $\begingroup$ Okay great! I'll do that, thanks for the help! $\endgroup$ Dec 16, 2016 at 10:26
3
$\begingroup$

Re: ReplacePart[a, pu -> 100], doesn't show the right result unfortunately:

You can use List/@pu -> 100 instead of pu -> 100

a = {0, 0, 0, 0, 0}; pu = {1, 4, 5};

ReplacePart[a, List /@ pu -> 100]

{100, 0, 0, 100, 100}

You can also use MapAt:

MapAt[100 &, a, List /@ pu]

{100, 0, 0, 100, 100}

$\endgroup$
2
$\begingroup$
a = {0, 0, 0, 0, 0};

p = {1, 4, 5};

Using ReplaceAt (new in 13.1)

f = ReplaceAt[_ :> 100, List /@ p];

f @ a

{100, 0, 0, 100, 100}

With ApplyTo (new in 12.2) we can change a inline (like in the accepted answer)

a //= f;

a

{100, 0, 0, 100, 100}

ReplaceAt has the advantage that we can easily impose conditions

a = {0, Missing[], 0, 0, 0};

p = {1, 4, 5};

ReplaceAt[_?NumberQ :> 100, List /@ p] @ a

{100, Missing[], 0, 100, 100}

$\endgroup$
2
$\begingroup$
a = {0, 0, 0, 0, 0};

p = {1, 4, 5};

Using SubsetMap:

SubsetMap[100 + # &, a, p]

(*{100, 0, 0, 100, 100}*)
$\endgroup$
2
  • 1
    $\begingroup$ One of my favourite functions cleverly employed :) $\endgroup$
    – eldo
    Feb 24 at 13:17
  • $\begingroup$ Thanks, @eldo! It's also one of my favorite functions ;) $\endgroup$ Feb 24 at 13:22

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.