In MATLAB, data is represented in the form of matrices and arrays. It’s used to create and manipulate arrays. MATLAB supports both one-dimensional and multi-dimensional arrays. In this shot, we’ll discuss the various methods of creating arrays.
MATLAB allows explicit array creation. Users create an array of specified size and dimensions. This is explained in the code below:
// Creating one-dimensional array
X = [1 2 3]
// Creating two-dimension array
Y = [1 2 3;
4 5 6;]
MATLAB has built-in methods for creating arrays. Some of them are explained below.
The zeros()
function creates an array of all zeros. The size of the array is specified within the parenthesis.
// Create an zeros array of size NxN => zeros(N)
X = zeros(3)
// [0 0 0
// 0 0 0
// 0 0 0]
// Creates an array of zeros of size 3x3
// Create an zeros array of size NxM => zeros(N,M)
X = zeros(2,5)
// Creates an array of zeros of size 2x5
// [0 0 0 0 0
// 0 0 0 0 0]
The ones()
function creates an array of all ones. The size of the array is specified within the parenthesis.
// Create an ones array of size NxN => ones(N)
X = ones(3)
// [1 1 1
// 1 1 1
// 1 1 1]
// Creates an array of ones of size 3x3
// Create an ones array of size NxM => ones(N,M)
X = ones(2,5)
// Creates an array of ones of size 2x5
// [1 1 1 1 1
// 1 1 1 1 1]
The eye()
function creates an array of all ones on diagonal, and zeros on other positions. The size of the array is specified within the parenthesis.
// Create an identity array/matrix of size NxN => eye(N)
X = eye(3)
// Creates an identity array/matrix of size 3x3
// [1 0 0
// 0 1 0
// 0 0 1]
// Create an identity array/matrix of size NxM => eye(N,M)
X = eye(3,4)
// Creates an identity array/matrix of size 3x4
// [1 0 0 0
// 0 1 0 0
// 0 0 1 0]
A magic square is a matrix that produces the same sum when the elements are added row-wise, column-wise, or diagonally.
The magic()
function creates a magic array. The size of the array is specified within the parenthesis.
// Create an magic square of size NxN => magic(N)
X = magic(3)
// Creates a magic square of size 3x3
// Example
// [ 8 1 6
// 3 5 7
// 4 9 2 ]
// The sum along all rows, columns and the diagonal is 15.
The rand()
function creates an array of random numbers. The size of the array is specified within the parenthesis.
// Create a random array of size NxN => rand(N)
X = rand(5)
// Creates an array of random numbers of size 5x5
// Example
// [0.156408 0.869683 0.030914 0.926079 0.405138
// 0.703914 0.361988 0.108234 0.155631 0.065869
// 0.542792 0.810626 0.147809 0.346073 0.767185
// 0.095147 0.949584 0.369915 0.216922 0.501125
// 0.683097 0.753033 0.114473 0.134470 0.868770]
// Create a random array of size NxM => rand(N,M)
X = rand(5,2)
// Creates an array of random numbers of size 5x2
//Example
// [0.4839 0.9188
// 0.4153 0.4916
// 0.7115 0.8949
// 0.2663 0.6541
// 0.2809 0.1629]