2
$\begingroup$

Let's have a list:

d={0.00144444, 17.6365, 6.68574, 22.5808, -1.85266, -11.1622, 100.021, 1.}

I want to replace some parts of it by zeroes: Documentation of ReplacePart says:

ReplacePart[expr,{i,j,…}->new]

replaces the part at position {i,j,…}. but

ReplacePart[d, {1, 4, 5, 6, 7} -> 0.0]

produces

{0.00144444, 17.6365, 6.68574, 22.5808, -1.85266, -11.1622, 100.021, 1.}

and to make things stranger

ReplacePart[d, {{1}, 4, 5, 6, 7} -> 0.0]
{0., 17.6365, 6.68574, 0., 0., 0., 0., 1.}

but

ReplacePart[d, {1, {4}, 5, 6, 7} -> 0.0]

During evaluation of ReplacePart::pkspec1: The expression {4} cannot be used as a part specification.
(* {0.00144444, 17.6365, 6.68574, 22.5808, -1.85266, -11.1622, \
100.021, 1.} *)

Is this a bug? What is the proper syntax for ReplacePart in my situation?

$\endgroup$
  • $\begingroup$ Anyway, I'm pretty sure that you want ReplacePart[data[[1, 1]], {{1}, {4}, {5}, {6}, {7}} -> 0.0] rather than ReplacePart[data[[1, 1]], {1, 4, 5, 6, 7} -> 0.0]? ReplacePart[data[[1, 1]], {{1}, 4, 5, 6, 7} -> 0.0] is weird, though. $\endgroup$ – march Aug 28 '17 at 17:57
  • $\begingroup$ @march I appologize, it was reckless, it has been corrected. The list to replace is 1 dimensional as was defined previously, the data[[1,1]] = d effectively. $\endgroup$ – leosenko Aug 28 '17 at 18:01
  • 1
    $\begingroup$ "replaces the part at position {i,j,…}" not "replaces parts at positions {i,j,…}" $\endgroup$ – Kuba Aug 28 '17 at 18:05
  • $\begingroup$ @Kuba Is that supposed to mean at position [[i,j,...]]? {i,j,..} specifies a list, not a position, no? $\endgroup$ – leosenko Aug 28 '17 at 18:07
  • $\begingroup$ @leosenko I'd look for tips in Position docs because [[]] is from Part. $\endgroup$ – Kuba Aug 28 '17 at 18:08
5
$\begingroup$

Why not use Part itself?

d = {0.00144444, 17.6365, 6.68574, 22.5808, -1.85266, -11.1622, 100.021, 1.}; 
d[[{1, 4, 5, 6, 7}]] = 0;

Now:

d
{0, 17.6365, 6.68574, 0, 0, 0, 0, 1.}

If you really want to use ReplacePart:

ReplacePart[d, Thread[{1, 4, 5, 6, 7} -> {0, 0, 0, 0, 0}]]

gives the same answer.

$\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.