0
$\begingroup$

This question already has an answer here:

I want to write a code like

X={};  
index=1;  
max=3;  
For[i=1,i<=2,i++,  
For[j=1,j<=2,j++,  
X[[index]]=i*j;  
index++  
]  
]  

But I am not getting correct result. Can anyone please help

$\endgroup$

marked as duplicate by Sascha, corey979, MarcoB, Feyre, m_goldberg Jan 12 '17 at 18:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    $\begingroup$ Presumably, you want either x=Array[#1*#2 &, {3, 3}] // Flatten or x=Table[i*j, {i, 3}, {j, 3}] // Flatten $\endgroup$ – Bob Hanlon Jan 11 '17 at 14:05
  • 1
    $\begingroup$ For sure, you don't want to use the For loop. $\endgroup$ – corey979 Jan 11 '17 at 14:17
  • $\begingroup$ I would use the Table solution proposed by @bob-hanlon $\endgroup$ – Valacar Jan 11 '17 at 14:29
  • $\begingroup$ Or Flatten@KroneckerProduct[#, #]&@Range@3 $\endgroup$ – Simon Rochester Jan 11 '17 at 20:28
3
$\begingroup$

Summary of methods. (Add yours if you have one not already here.)

Bob Hanlon

 Array[#1*#2 &, {3, 3}] // Flatten 
 Table[i*j, {i, 3}, {j, 3}] // Flatten

Simon Rochester

KroneckerProduct @@ Range[{3, 3}] // Flatten
Range[3] Range[{3, 3, 3}] // Flatten
Accumulate /@ Transpose@Range@ConstantArray[3, 3] // Flatten

m_goldberg

Range[3] ConstantArray[Range[3], 3] // Flatten
$\endgroup$

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