Understanding MATLAB Arrays and Functions

Previously, we discussed a lot about MATLAB vectors and matrices. In this chapter, we will discuss multidimensional arrays. In MATLAB, all variable data types are multidimensional arrays; a vector is a one-dimensional array, and a matrix is a two-dimensional array.

First, let’s look at some special types of arrays.

Special Arrays in MATLAB

In MATLAB, some functions are used to create special arrays. For all these functions, one parameter creates a square array, while two parameters create a rectangular array.

Use the zeros() function to create an array with elements equal to zero:

For example:

zeros(5)

MATLAB executes the above statement and returns 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

Use the ones() function to create an array:

For example:

ones(4,3)

MATLAB executes the above statement and returns the following result:

ans =     1     1     1     1     1     1     1     1     1     1     1     1

Use the eye() function to create a matrix:

For example:

eye(4)

MATLAB executes the above statement and returns the following result:

ans =     1     0     0     0     0     1     0     0     0     0     1     0     0     0     0     1

Use the rand() function to create an array of uniformly distributed random numbers between (0,1):

For example:

rand(3, 5)

MATLAB executes the above statement and returns 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

Magic Squares in MATLAB

A magic square is a square array of numbers where the sums of the numbers in each row, each column, and both main diagonals are the same.

Use the magic() function to create a magic square array. It requires a single odd parameter that must be a scalar greater than or equal to 3.

For example:

magic(4)

MATLAB executes the above statement and returns the following result:

ans =    16     2     3    13     5    11    10     8     9     7     6    12     4    14    15     1

Multidimensional Arrays in MATLAB

In MATLAB, an array with more than two dimensions is called a multidimensional array.

Multidimensional arrays in MATLAB are extensions of normal two-dimensional matrices.

In MATLAB, you first need to create a two-dimensional array and then extend that two-dimensional array to generate a multidimensional array.

For example, let’s first create a two-dimensional array a.

a = [7 9 5; 6 1 9; 4 3 2]

MATLAB executes the above statement and returns the following result:

a =     7     9     5     6     1     9     4     3     2

The array a is a 3×3 array. By providing values, we can add a third dimension, for example:

a(:, :, 2)= [ 1 2 3; 4 5 6; 7 8 9]

MATLAB executes the above statement and returns the following result:

a(:,:,1) =     7     9     5     6     1     9     4     3     2
a(:,:,2) =     1     2     3     4     5     6     7     8     9

Similarly, we can also use the ones(), zeros(), or rand() functions to create multidimensional arrays.

For example:

b = rand(4,3,2)

MATLAB executes the above statement and returns the following result:

b(:,:,1) =    0.0344    0.7952    0.6463    0.4387    0.1869    0.7094    0.3816    0.4898    0.7547    0.7655    0.4456    0.2760
b(:,:,2) =    0.6797    0.4984    0.2238    0.6551    0.9597    0.7513    0.1626    0.3404    0.2551    0.1190    0.5853    0.5060

You can also use the cat() function to create multidimensional arrays, which combines arrays along specified dimensions:

The syntax for the cat() function is:

B = cat(dim, A1, A2...)

Note:

  • B is the new array;

  • A1, A2, … are the arrays to be concatenated;

  • dim is the dimension along which to concatenate the arrays.

Detailed Example

Create a script file in MATLAB and input the following code:

a = [9 8 7; 6 5 4; 3 2 1];b = [1 2 3; 4 5 6; 7 8 9];c = cat(3, a, b, [ 2 3 1; 4 7 8; 3 9 0])

When you run this file, the displayed results are:

c(:,:,1) =     9     8     7     6     5     4     3     2     1c(:,:,2) =     1     2     3     4     5     6     7     8     9c(:,:,3) =     2     3     1     4     7     8     3     9     0

MATLAB Array Functions

MATLAB provides the following functions for sorting, rotating, shuffling, reshaping, or moving the contents of arrays.

Function Purpose
length Vector length or maximum array size
ndims Number of dimensions of the array
numel Number of elements in the array
size Array dimensions
iscolumn Determine if the input is a column vector
isempty Determine if the array is empty
ismatrix Determine if the input is a matrix
isrow Determine if the input is a row vector
isscalar Determine if the input is a scalar
isvector Determine if the input is a vector
blkdiag Construct block diagonal matrix from input parameters
circshift Circular shift
ctranspose Complex conjugate transpose
diag Diagonal matrix and diagonal of a matrix
flipdim Flip array along specified dimension
fliplr Flip matrix from left to right
flipud Flip matrix upside down
ipermute Inverse permutation of dimensions of n-dimensional array
permute Rearrange dimensions of n-dimensional array
repmat Replicate and tile an array
reshape Reshape an array
rot90 Rotate matrix 90 degrees
shiftdim Shift dimensions
issorted Determine if the elements of the set are sorted
sort Sort array elements in ascending or descending order
sortrows Sort rows in ascending order
squeeze Remove singleton dimensions
transpose Transpose
vectorize Vectorize expression

Detailed Example

Some of the above functions will be illustrated by the following examples.

Length, size, and number of elements:

Create a script file in MATLAB and input the following code:

x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];length(x)  % length of x vectory = rand(3, 4, 5, 2);ndims(y)    % no of dimensions in array ys = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];numel(s)   % no of elements in s

When running this file, the displayed results are:

ans =     8ans =     4ans =    23

Circular shifting of array elements:

Create a script file in MATLAB and input the following code:

a = [1 2 3; 4 5 6; 7 8 9]  % the original array ab = circshift(a,1)  %  circular shift first dimension values down by 1.c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1                          % and second dimension values to the left % by 1.

When running this file, the displayed results are:

a =     1     2     3     4     5     6     7     8     9
b =     7     8     9     1     2     3     4     5     6
c =     8     9     7     2     3     1     5     6     4

Sorting MATLAB Arrays

Create a script file in MATLAB and input the following code:

v = [ 23 45 12 9 5 0 19 17]  % horizontal vectorsort(v)   %sorting vm = [2 6 4; 5 3 9; 2 0 1]  %  two dimensional arraysort(m, 1)   % sorting m along the rowsort(m, 2)   % sorting m along the column

When running this file, the displayed results are:

v =    23    45    12     9     5     0    19    17ans =     0     5     9    12    17    19    23    45m =     2     6     4     5     3     9     2     0     1ans =     2     0     1     2     3     4     5     6     9ans =     2     4     6     3     5     9     0     1     2

Cell Arrays in MATLAB

Cell arrays are arrays where each cell can store arrays of different dimensions and data types.

The cell function is used to create a cell array.

The syntax of the cell function is as follows:

C = cell(dim)C = cell(dim1,...,dimN)D = cell(obj)

Note

  • C is the cell array;

  • dim is a scalar integer or integer vector specifying the size of the cell array C;

  • dim1, … , dimN are scalar integers specifying the size of C;

  • obj is one of the following:

    • Java array or object

    • .NET array of type System.String or System.Object

Detailed Example

Create a script file in MATLAB and input the following code:

c = cell(2, 5);c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5}

When running this file, the displayed results are:

c =     'Red'    'Blue'    'Green'    'Yellow'    'White'    [  1]    [   2]    [    3]    [     4]    [    5]

Accessing Data in Cell Arrays in MATLAB

Use two methods to reference elements of a cell array:

  • Enclosed indexing in the first bracket () refers to a group of cells

  • Enclosed indexing in curly braces {}, refers to the data in a single cell

Indexing in the first bracket refers to a set of cells.

Cell array indexing smooths the collection of cells.

For example:

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};c(1:2,1:2)

MATLAB executes the above statement and returns the following result:

ans =     'Red'    'Blue'    [  1]    [   2]

You can also use curly braces { } to index and access the contents of the cell.

For example:

c = {'Red', 'Blue', 'Green', 'Yellow', 'White'; 1 2 3 4 5};c{1, 2:4}

MATLAB executes the above statement and returns the following result:

ans =   Blueans =   Greenans =   Yellow

Leave a Comment