3

I have a list {a,b,c,d}, and I want to set the 1st element and the 3rd elements equal to 5 and 8, respectively, leaving 2nd and 4th as they are ({b,d} used later). How is this done?

Later, I want to set the 2nd element and the 4th element to other numbers, then 1st and 2nd, and so on... I spent a lot of time working on this (yup, embarrassed) but cant find a solution.

Kuba
  • 136,707
  • 13
  • 279
  • 740
Nari Nare
  • 31
  • 1

2 Answers2

1

It is better to use indexed variable for this kind of manipulations. See related topics for a background of what is about to happen: 40663, 70250.

You can do:

set // Attributes = {HoldFirst};
set[varList_, pos_, values_] := (
  Hold[varList] /. OwnValues[varList]
)[[{1}, pos]] /. Hold[vars_] :> Hold[vars = values] // ReleaseHold

Which is far from being neat but it works.

{a, b, c, d, e} = Range[5];
varList := {a, b, c, d, e};


varList

set[varList, {1, 3}, {15, 15}];
varList

set[varList, 2 ;;, {1, 11, 111, 111}];
varList
{1, 2, 3, 4, 5}

{15, 2, 15, 4, 5}

{15, 1, 11, 111, 111}

Kuba
  • 136,707
  • 13
  • 279
  • 740
0

As Kuba mentioned, it is better to use an indexed variable, so here are a couple of examples.

Clear[i]

list = i /@ Range[4]
{i[1], i[2], i[3], i[4]}
(i[#1] = #2) & @@@ {{1, 5}, {3, 8}};

i /@ Range[4]
{5, i[2], 8, i[4]}
Clear[x]

With[{x = i /@ {2, 4}}, x = {7, 9}];

list
{5, 7, 8, 9}
Array[i, 4]
{5, 7, 8, 9}
Chris Degnen
  • 30,927
  • 2
  • 54
  • 108