Array Indexing - MATLAB & Simulink

Array Indexing

 

Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected elements of an array, use indexing.

For example, consider the 4-by-4 magic square A:

A = magic(4)
A = 4×4

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

There are two ways to refer to a particular element in an array. The most common way is to specify row and column subscripts, such as

A(4,2)
ans = 14

Less common, but sometimes useful, is to use a single subscript that traverses down each column in order:

A(8)
ans = 14

Using a single subscript to refer to a particular element in an array is called linear indexing.

If you try to refer to elements outside an array on the right side of an assignment statement, MATLAB throws an error.

test = A(4,5)

Index exceeds matrix dimensions.

However, on the left side of an assignment statement, you can specify elements outside the current dimensions. The size of the array increases to accommodate the newcomers.

A(4,5) = 17
A = 4×5

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

To refer to multiple elements of an array, use the colon operator, which allows you to specify a range of the form start:end. For example, list the elements in the first three rows and the second column of A:

A(1:3,2)
ans = 3×1

     2
    11
     7

The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all the columns in the third row of A:

A(3,:)
ans = 1×5

     9     7     6    12     0

The colon operator also allows you to create an equally spaced vector of values using the more general form start:step:end.

B = 0:10:100
B = 1×11

     0    10    20    30    40    50    60    70    80    90   100

If you omit the middle step, as in start:end, MATLAB uses the default step value of 1.

Indexing with Element Positions

The most common way is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element.

A = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
A = 4×4

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

e = A(3,2)
e = 10

e is the element in the 3,2 position (third row, second column) of A.

You can also reference multiple elements at a time by specifying their indices in a vector. For example, access the first and third elements of the second row of A.

r = A(2,[1 3])
r = 1×2

     5     7

To access elements in a range of rows or columns, use the colon. For example, access the elements in the first through third row and the second through fourth column of A.

r = A(1:3,2:4)
r = 3×3

     2     3     4
     6     7     8
    10    11    12

An alternative way to compute r is to use the keyword end to specify the second column through the last column. This approach lets you specify the last column without knowing exactly how many columns are in A.

r = A(1:3,2:end)
r = 3×3

     2     3     4
     6     7     8
    10    11    12

If you want to access all of the rows or columns, use the colon operator by itself. For example, return the entire third column of A.

r = A(:,3)
r = 4×1

     3
     7
    11
    15

In general, you can use indexing to access elements of any array in MATLAB regardless of its data type or dimensions. For example, directly access a column of a datetime array.

t = [datetime(2018,1:5,1); datetime(2019,1:5,1)]
t = 2x5 datetime
   01-Jan-2018   01-Feb-2018   01-Mar-2018   01-Apr-2018   01-May-2018
   01-Jan-2019   01-Feb-2019   01-Mar-2019   01-Apr-2019   01-May-2019

march1 = t(:,3)
march1 = 2x1 datetime
   01-Mar-2018
   01-Mar-2019

For higher-dimensional arrays, expand the syntax to match the array dimensions. Consider a random 3-by-3-by-3 numeric array. Access the element in the second row, third column, and first sheet of the array.

A = rand(3,3,3);
e = A(2,3,1)
e = 0.5469

For more information on working with multidimensional arrays, see Multidimensional Arrays.

Indexing with a Single Index

Another method for accessing elements of an array is to use only a single index, regardless of the size or dimensions of the array. This method is known as linear indexing. While MATLAB displays arrays according to their defined sizes and shapes, they are actually stored in memory as a single column of elements. A good way to visualize this concept is with a matrix. While the following array is displayed as a 3-by-3 matrix, MATLAB stores it as a single column made up of the columns of A appended one after the other. The stored vector contains the sequence of elements 124533362925914811, and can be displayed using a single colon.

A = [12 36 91; 45 29 48; 33 25 11]
A = 3×3

    12    36    91
    45    29    48
    33    25    11

Alinear = A(:)
Alinear = 9×1

    12
    45
    33
    36
    29
    25
    91
    48
    11

For example, the 3,2 element of A is 25, and you can access it using the syntax A(3,2). You can also access this element using the syntax A(6), since 25 is sixth element of the stored vector sequence.

e = A(3,2)
e = 25
elinear = A(6)
elinear = 25

While linear indexing can be less intuitive visually, it can be powerful for performing certain computations that are not dependent on the size or shape of the array. For example, you can easily sum all of the elements of A without having to provide a second argument to the sum function.

s = sum(A(:))
s = 330

The sub2ind and ind2sub functions help to convert between original array indices and their linear version. For example, compute the linear index of the 3,2 element of A.

linearidx = sub2ind(size(A),3,2)
linearidx = 6

Convert from the linear index back to its row and column form.

[row,col] = ind2sub(size(A),6)
row = 3
col = 2

Indexing with Logical Values

Using true and false logical indicators is another useful way to index into arrays, particularly when working with conditional statements. For example, say you want to know if the elements of a matrix A are less than the corresponding elements of another matrix B. The less-than operator returns a logical array whose elements are 1 when an element in A is smaller than the corresponding element in B.

A = [1 2 6; 4 3 6]
A = 2×3

     1     2     6
     4     3     6

B = [0 3 7; 3 7 5]
B = 2×3

     0     3     7
     3     7     5

ind = A<B
ind = 2x3 logical array

   0   1   1
   0   1   0

Now that you know the locations of the elements meeting the condition, you can inspect the individual values using ind as the index array. MATLAB matches the locations of the value 1 in ind to the corresponding elements of A and B, and lists their values in a column vector.

Avals = A(ind)
Avals = 3×1

     2
     3
     6

Bvals = B(ind)
Bvals = 3×1

     3
     7
     7

MATLAB "is" functions also return logical arrays that indicate which elements of the input meet a certain condition. For example, check which elements of a string vector are missing using the ismissing function.

str = ["A" "B" missing "D" "E" missing];
ind = ismissing(str)
ind = 1x6 logical array

   0   0   1   0   0   1

Suppose you want to find the values of the elements that are not missing. Use the ~ operator with the index vector ind to do this.

strvals = str(~ind)
strvals = 1x4 string
    "A"    "B"    "D"    "E"

Matlabsolutions.com provides guaranteed satisfaction with a commitment to complete the work within time. Combined with our meticulous work ethics and extensive domain experience, We are the ideal partner for all your homework/assignment needs. We pledge to provide 24*7 support to dissolve all your academic doubts. We are composed of 300+ esteemed Matlab and other experts who have been empanelled after extensive research and quality check.

Matlabsolutions.com provides undivided attention to each Matlab assignment order with a methodical approach to solution. Our network span is not restricted to US, UK and Australia rather extends to countries like Singapore, Canada and UAE. Our Matlab assignment help services include Image Processing Assignments, Electrical Engineering Assignments, Matlab homework help, Matlab Research Paper help, Matlab Simulink help. Get your work done at the best price in industry.

Machine Learning in MATLAB

Train Classification Models in Classification Learner App

Train Regression Models in Regression Learner App

Distribution Plots

Explore the Random Number Generation UI

Design of Experiments

Machine Learning Models

Logistic regression

Logistic regression create generalized linear regression model - MATLAB fitglm 2

Support Vector Machines for Binary Classification

Support Vector Machines for Binary Classification 2

Support Vector Machines for Binary Classification 3

Support Vector Machines for Binary Classification 4

Support Vector Machines for Binary Classification 5

Assess Neural Network Classifier Performance

Naive Bayes Classification

ClassificationTree class

Discriminant Analysis Classification

Ensemble classifier

ClassificationTree class 2

Train Generalized Additive Model for Binary Classification

Train Generalized Additive Model for Binary Classification 2

Classification Using Nearest Neighbors

Classification Using Nearest Neighbors 2

Classification Using Nearest Neighbors 3

Classification Using Nearest Neighbors 4

Classification Using Nearest Neighbors 5

Linear Regression

Linear Regression 2

Linear Regression 3

Linear Regression 4

Nonlinear Regression

Nonlinear Regression 2

Visualizing Multivariate Data

Generalized Linear Models

Generalized Linear Models 2

RegressionTree class

RegressionTree class 2

Neural networks

Gaussian Process Regression Models

Gaussian Process Regression Models 2

Understanding Support Vector Machine Regression

Understanding Support Vector Machine Regression 2

RegressionEnsemble