4
$\begingroup$

I have a function

y[k_]:={0,0,0,I*t^k};

and I need to get a vector

Join[y[1],y[2],y[3],y[4],y[5],y[6],y[7]]

and it is just for instance. The real vector I am using is much more complicated, and there are more y[k]s. I realized that manually typing the Join part is inefficient and tiring.

How can I achieve my goal with a short code? Maybe involve Nest or Do. Thank you.

$\endgroup$
6
$\begingroup$
Array[y, 7, 1, Join]

{0, 0, 0, I t, 0, 0, 0, I t^2, 0, 0, 0, I t^3, 0, 0, 0, I t^4, 0, 0, 0, I t^5, 0, 0, 0, I t^6, 0, 0, 0, I t^7}

| improve this answer | |
$\endgroup$
  • $\begingroup$ Really equisite! Thank you! $\endgroup$ – Robin_Lyn Jul 6 '18 at 11:05
  • $\begingroup$ @Robin_Lyn, my pleasure. Thank you for the accept. $\endgroup$ – kglr Jul 6 '18 at 11:05
2
$\begingroup$

Try with the following code:

y[k_] := {0, 0, 0, I*t^k};

test1 = Join[y[1], y[2], y[3], y[4], y[5], y[6], y[7]];

test2 = Join @@ y /@ Range[7]

test1 == test2

{0, 0, 0, I t, 0, 0, 0, I t^2, 0, 0, 0, I t^3, 0, 0, 0, I t^4, 0, 0, 0, I t^5, 0, 0, 0, I t^6, 0, 0, 0, I t^7}

True

Instead of Range[7] you can use any list of arguments you need.

EDIT:

comparison between my solution and kglr solution:

RepeatedTiming@Array[y, 10000, 1, Join] // First
RepeatedTiming@(Join @@ y /@ Range[10000]) // First

0.018

0.019

Basically the same performance :)

Personally, I'd probably use kglr solution for consecutive values of the argument, mine in case I need more tunability in the argument's values

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ Good alternative to kglr's solution. Thank you! People in this forum are really friendly. $\endgroup$ – Robin_Lyn Jul 6 '18 at 11:07
  • $\begingroup$ You are welcome :) $\endgroup$ – Fraccalo Jul 6 '18 at 11:10

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.