0
$\begingroup$

I'm trying to create an n*n matrix that would follow this criteria

1    2    3   ...  n
n+1  n+2  n+3 ...  2n
2n+1 2n+2 2n+3 ... 3n
 .                  .
 .                  .
 .                  .
(n-1)n+1 ........ n^2

How would I be able to create this matrix using a table or a do loop? This is what I've created so far, but it doesn't follow the criteria unfortunately.

n = Input["What positive integer would you like to start your matrix with?"];
x = ConstantArray[0, {n, n}];
Do[x[[i, j]] = i + j, {i, 1, n}, {j, 1, n}]
x // MatrixForm
$\endgroup$
3
  • 8
    $\begingroup$ Why not use Partition[Range[n^2], n]? $\endgroup$
    – Carl Woll
    Commented Feb 16, 2017 at 17:17
  • 3
    $\begingroup$ you didn't like the answers over here: stackoverflow.com/q/42240155/1004168 ? $\endgroup$
    – george2079
    Commented Feb 16, 2017 at 20:06
  • $\begingroup$ This is a version of (111631) $\endgroup$
    – Mr.Wizard
    Commented Feb 18, 2017 at 2:55

2 Answers 2

5
$\begingroup$

Better to use Table:

n = Input["What positive integer would you like to start your matrix with?"];

Table[i + j*n, {j, 0, n - 1}, {i, n}]
$\endgroup$
3
$\begingroup$

I suggest you define a function, m to create your matrix. Here are two possible for m

Carl Woll

m[n_] := Partition[Range[n^2], n]

m_goldberg

m[n_] := ArrayReshape[Range[n^2], {n, n}]

In either case

m[3]//MatrixForm

matrix

$\endgroup$

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