MATLAB - Arrays



Prev TutorialNext Tutorial

All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss multidimensional arrays. However, before that, let us discuss some special types of arrays.

Special Arrays in MATLAB

In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.
The zeros() function creates an array of all zeros −
For example −

zeros(5)
MATLAB will execute the above statement and return the following result −
ans =
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
     0     0     0     0     0
The ones() function creates an array of all ones −
For example −

ones(4,3)
MATLAB will execute the above statement and return the following result −
ans =
     1     1     1
     1     1     1
     1     1     1
     1     1     1
The eye() function creates an identity matrix.
For example −

eye(4)
MATLAB will execute the above statement and return the following result −
ans =
     1     0     0     0
     0     1     0     0
     0     0     1     0
     0     0     0     1
The rand() function creates an array of uniformly distributed random numbers on (0,1) −
For example −

rand(3, 5)
MATLAB will execute the above statement and return the following result −
ans =
    0.8147    0.9134    0.2785    0.9649    0.9572
    0.9058    0.6324    0.5469    0.1576    0.4854
    0.1270    0.0975    0.9575    0.9706    0.8003

A Magic Square

magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.
The magic() function creates a magic square array. It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.

magic(4)
MATLAB will execute the above statement and return the following result −
ans =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

Prev TutorialNext Tutorial