In MATLAB, you can create a matrix with elements from 1 to n using the following methods:
Using the colon notation:
1 2 3 4 | n = 5; A = reshape(1:n^2, [n,n]) % creates a nxn matrix with elements from 1 to n^2 |
Using the meshgrid function:
1 2 3 4 5 | n = 5; [X,Y] = meshgrid(1:n); A = [X(:) Y(:)]; % creates a nxn matrix with elements from 1 to n |
Using the reshape function:
1 2 3 4 | n = 5; A = reshape(1:n^2, [n,n]) % creates a nxn matrix with elements from 1 to n^2 |
Using the repmat function:
1 2 3 4 | n = 5; A = repmat(1:n, n, 1) % creates a nxn matrix with elements from 1 to n |
Using the bsxfun function :
1 2 3 4 | n = 5; A = bsxfun(@plus, (1:n)', 0:n-1) % creates a nxn matrix with elements from 1 to n |
You may also like: MATLAB Array Examples
Using a for loop:
1 2 3 4 5 6 7 8 9 | n = 5; A = zeros(n); for i = 1:n for j = 1:n A(i,j) = (i-1)*n + j; end end |
Note that, the above methods will create a matrix of size nxn with elements from 1 to n^2. You can adjust the methods to suit your requirements.