13

I have a list:

mainlist={0.23, 0.34, 0.8, 0.0, -0.2, 0.4, -0.1};

I have to extend the above list to another one finalresult with Length=17. But in finalresult the elements of the mainlist must be in the positions ruled by the positionlist:

positionlist={3,4,8,9,10,13,14};

finalresult={0,0,0.23,0.34,0,0,0,0.8,0.0,-0.2,0,0,0.4,-0.1,0,0,0}

How can I reach this goal? I would be so glad to see an answer.

Inzo Babaria
  • 1,513
  • 7
  • 11

5 Answers5

16
Normal@SparseArray[Thread[positionlist -> mainlist], 17, 0]

Update: should emphasize C.E.'s nice comment:

Normal@SparseArray[positionlist -> mainlist, 17]

equivalent in result, more pleasantly laconic, and lack of explicit thread actually less expensive for longer lists.

7
mainlist={0.23, 0.34, 0.8, 0.0, -0.2, 0.4, -0.1};
positionlist={3,4,8,9,10,13,14};

ReplacePart[ConstantArray[0, 17], Thread[positionlist -> mainlist]]

or what @Carl Woll suggested:

finalresult = ConstantArray[0, 17];
finalresult[[positionlist]] = mainlist
Ali Hashmi
  • 8,950
  • 4
  • 22
  • 42
3
list = {0.23, 0.34, 0.8, 0.0, -0.2, 0.4, -0.1};

p = {3, 4, 8, 9, 10, 13, 14};

Using SubsetMap (new in 12.0)

SubsetMap[list &, Table[0, 17], p]

{0, 0, 0.23, 0.34, 0, 0, 0, 0.8, 0., -0.2, 0, 0, 0.4, -0.1, 0, 0, 0}

eldo
  • 67,911
  • 5
  • 60
  • 168
2

Using Fold:

Clear["Global`"];
mainlist = {0.23, 0.34, 0.8, 0.0, -0.2, 0.4, -0.1};
positionlist = {3, 4, 8, 9, 10, 13, 14};

rules = Rule @@@ Transpose[{positionlist, mainlist}]; Fold[ReplacePart[#1, #2] &, Table[0, 17], rules]

{0, 0, 0.23, 0.34, 0, 0, 0, 0.8, 0., -0.2, 0, 0, 0.4, -0.1, 0, 0, 0}

Syed
  • 52,495
  • 4
  • 30
  • 85
1
list = {0.23, 0.34, 0.8, 0.0, -0.2, 0.4, -0.1};

p = {3, 4, 8, 9, 10, 13, 14};

An alternative using Cases and If:

rep = Rule @@@ Thread[{p, list}];

Cases[Range[17], x_ :> If[And @@ (Unequal[x, #] & /@ p), 0, x /. rep]]

({0, 0, 0.23, 0.34, 0, 0, 0, 0.8, 0., -0.2, 0, 0, 0.4, -0.1, 0, 0, 0})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44