Nxn matrix with elements between 1...n^2

Hi everyone. I have to do a nxn matrix, whose elements are natural numbers between 1...n^2. For example, if n=3 the matrix will be:
[1 2 3; 4 5 6; 7 8 9]
Also, I have to be able to order the matrix by rows or columns.
Of course, thanks. I'm just starting with the Matlab world and it's not easy lol.

 採用された回答

Chad Greene
Chad Greene 2015 年 6 月 12 日

1 投票

Here's one way:
n = 3;
% Create a 1D array of all the values:
m = 1:n^2;
% Reshape m into nxn:
m = reshape(m,n,n)

3 件のコメント

Facundo Beer
Facundo Beer 2015 年 6 月 12 日
Thanks a lot! Now, with this method matlab orders the matrix by columns. How could I order it by rows?
James Tursa
James Tursa 2015 年 6 月 12 日
m = m';
Chad Greene
Chad Greene 2015 年 6 月 12 日
Ah, oops! Thanks James.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by