1
$\begingroup$

I'm having trouble trying to manipulate a function in a type of "loop" format. Essentially what I want to do is be able to manipulate the amount of Append functions I use. For example:

data={3,4,5,1,5,2,4}

Append[data,0]={3,4,5,1,5,2,4,0}

Append[Append[data,0],0]={3,4,5,1,5,2,4,0,0}

Append[Append[Append[data,0],0],0]={3,4,5,1,5,2,4,0,0,0}

and so on...

I was wondering if there was an easy way to manipulate the number of Append/Prepend functions I use to that it is as simple as typing 1 or 2 into a line of code to get the number of Append/Prepend functions I apply to that particular dataset.

Thanks!

$\endgroup$
  • $\begingroup$ See Nest, but here PadRight looks better. $\endgroup$ – Kuba Jul 31 '17 at 20:51
2
$\begingroup$
data = {3, 4, 5, 1, 5, 2, 4};

ArrayPad[data, {0, 3}]

or

{##, Sequence[0, 0, 0]} & @@ data

give

{3, 4, 5, 1, 5, 2, 4, 0, 0, 0}

Prepending:

ArrayPad[data, {3, 0}, x]

{x, x, x, 3, 4, 5, 1, 5, 2, 4}

$\endgroup$
  • $\begingroup$ This is exactly what I needed, thanks a lot! $\endgroup$ – jeff Jul 31 '17 at 21:03
  • $\begingroup$ You're welcome - thanks for acceptance $\endgroup$ – eldo Jul 31 '17 at 21:07
1
$\begingroup$
Nest[Append[#, 0] &, data, 3] 

switch to Prepend for the equivalent result.

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