1
$\begingroup$

I am trying to fill a vector starting from component 11 from another vector, I use this code:

Do[AppendTo[xp, x[[i + 10]]], {i, 1, 99982}]

How can I fill xp without using `AppendTo'?

$\endgroup$
  • 6
    $\begingroup$ xp=x[[11;;99992]]? $\endgroup$ – xzczd Jul 17 at 6:06
  • 1
    $\begingroup$ Not totally sure if this is what you want: xp=x[[10;;]], maybe $\endgroup$ – mgamer Jul 17 at 6:06
  • 4
    $\begingroup$ You can use xp={};Do[xp=Join[xp,{x[[i+10]]}],{i,1,9982}]. It works much faster than with AppendTo. $\endgroup$ – Rom38 Jul 17 at 6:35
  • 2
    $\begingroup$ @Rom38 I'm not sure why that works faster for you. I don't think it should because it still has the same problem as OP's solution. That is, growing the size of the array (i.e. allocating more memory) on every update. That's what's slow. AppendTo and Join both have this problem. Solutions that don't have this result are i.e. bags, Sow, pre-allocating memory and assigning using Part. In practice, it often turns out that growing the list dynamically is unnecessary, or can be solved by using e.g. Table which pre-allocates memory, but we can't tell if that is possible without context. $\endgroup$ – C. E. Jul 17 at 7:55
  • 2
    $\begingroup$ @C.E. You can test with long enough list, it is easy. The Join works faster. $\endgroup$ – Rom38 Jul 17 at 12:41
2
$\begingroup$

If you want xp just to be the values of x from component 11 you can use xp = x[[11;;]]. If xp is already defined, has some values and you want to append the values of x, starting from component 11 then Join[ xp , x[[11;;]] ] should do the trick.

| improve this 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.