1
$\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
    $\begingroup$ Try with Thread[pu -> 100] or Transpose[{pu}] -> 100. $\endgroup$ – J. M. is away Dec 16 '16 at 9:30
3
$\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$
  • $\begingroup$ Thank you so much for the solution and the quick respons!! $\endgroup$ – Carlijn Bakker Dec 16 '16 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$ – Mauricio Fernández Dec 16 '16 at 9:58
  • $\begingroup$ Okay great! I'll do that, thanks for the help! $\endgroup$ – Carlijn Bakker Dec 16 '16 at 10:26
0
$\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$

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.