0
$\begingroup$

Note: In my code I used j (ranging from 3 to 7) but I want j to be general

I tried this

i = 0;
For[j = 3, j < 10, j++,
 q[[i++]] = 2 + j]
q

Error: Symbol q in part assignment does not have an immediate value

I also tried initializing q

i = 0;
q = {0, 0, 0, 0, 0, 0, 0};
For[j = 3, j < 10, j++,
 q[[i++]] = 2 + j]
q

Output: 5[6, 7, 8, 9, 10, 11, 0]

I didn't understand why 5 is outside in 5[6, 7, 8, 9, 10, 11, 0].In output, q doesn't look like Table.

Ok well!! while writing this I was checking suggestions and could solve it, I tried

i = 0;
q = {};
For[j = 3, j < 10, j++,
 temp = 2 + j;
 AppendTo[q, temp];]
q

Is this a good way to do or are there even simple methods to code?

$\endgroup$
2
  • 2
    $\begingroup$ q = Range[5, 11]. See here for how to use loops in Mathematica (Hint: don't.). Also see here for how to avoid common pitfalls in MMA. Also: the weirdness in your second example is caused by using i++. Try ++i instead. $\endgroup$
    – march
    Sep 14, 2015 at 19:06
  • $\begingroup$ Thanks for reminding the difference between post and pre increments $\endgroup$ Sep 14, 2015 at 19:10

1 Answer 1

3
$\begingroup$

You need to initialize i to be 1 rather than 0.

i = 1;
q = {0, 0, 0, 0, 0, 0, 0};

For[j = 3, j < 10, j++,
 q[[i++]] = 2 + j];

q

This yields

{5, 6, 7, 8, 9, 10, 11}

In the step where you initialize q you could have used:

q = ConstantArray[0, 7];

However a much better approach is to use the comment from march. Use the Range function and you are done in one step.

q = Range[5,11]

Please do read the links that he provided you about loops.

$\endgroup$
1
  • $\begingroup$ +1. Now why is i == 0 causing trouble? My favorite explanation: 86189 $\endgroup$
    – C. E.
    Sep 14, 2015 at 20:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.