13
$\begingroup$

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.

$\endgroup$
  • 6
    $\begingroup$ I expect somebody to reference a duplicate, but you can use finalresult = ConstantArray[0, 17]; finalresult[[positionlist]]=mainlist in the meantime. $\endgroup$ – Carl Woll Aug 26 '17 at 14:23
  • 1
    $\begingroup$ Related: (30339), (30647), (31648), (41877), (147876) $\endgroup$ – Mr.Wizard Aug 26 '17 at 21:01
  • $\begingroup$ @CarlWoll I looked but I was unable to find a duplicate. Perhaps you would care to convert your comment to an answer, in the mean time. :^) $\endgroup$ – Mr.Wizard Aug 26 '17 at 21:33
15
$\begingroup$
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.

$\endgroup$
  • 7
    $\begingroup$ +1. Thread and the zero at the end can be omitted. $\endgroup$ – C. E. Aug 26 '17 at 14:27
  • 1
    $\begingroup$ A usage note regarding the performance of this method: (148112) $\endgroup$ – Mr.Wizard Aug 26 '17 at 21:15
5
$\begingroup$
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
$\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.