Create a matrix using the following code:
A = magic(3);
A = 8 1 6 3 5 7 4 9 2
The syntax to use logical indexing is
A is the matrix being accessed and
B is a logical matrix.
% Logical indexing expression r = A(A>7);
r = 8 9
Requirement: The number of elements in the logical matrix
B must be lower than or equal to the number of elements in the matrix being accessed
A. In practice, they have the same shape normally.
How it works
MATLAB processes logical indexing expressions
A(B) as follows (Fig. 1):
- Get both matrices in the form that they are stored in memory
Bhas less elements than
A, assume the missing values as
- Find the elements in
% Elements greater than 3 in the first two columns of A expExample1 = A > 3; expExample1(:,3) = false; resultExample1 = A(expExample1);
resultExample1 = 8 4 5 9
% Elements greater than 4 in odd linear positions expExample2 = A > 4; expExample2(2:2:end) = false; resultExample2 = A(expExample2);
resultExample2 = 8 5 6
% Set to 0 the elements greater than 5 in the 1st/3rd rows expExample3 = A > 5; expExample3(2,:) = false; A(expExample3) = 0;
A = 0 1 0 3 5 7 4 0 2
I recommend the following books to learn more on logical indexing in MATLAB:
This book was the winner of a 2017 Textbook Excellence Award. Logical indexing, and other indexing methods, are explained clearly in the second chapter.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The fourth chapter is completely dedicated to matrix manipulation.
I also recommend the other tutorials in this series.
- Subscript Indexing in MATLAB
- How MATLAB Stores Matrices in Memory
- Linear Indexing in MATLAB
- How to Convert Linear Indices to Subscripts and Viceversa in MATLAB
- MATLAB end Keyword in Matrix Indexing Expressions
- Logical Indexing in MATLAB
- A Deeper Look on Logical Indexing in MATLAB
- MATLAB Colon Operator in Matrix Indexing Expressions
Consult the help documentation of the
rand function. Create a matrix of random numbers having three rows, four columns, and two planes, and get the values:
- Greater than 0.5 in the first column of each plane
- Lower than 0.5 in the last two columns of the second plane
- Greater than 0.25 and lower than 0.75 in linear positions multiple of 3
A possible solution could be:
doc rand; X = rand(3,4,2); % Clause 1 expClause1 = X > 0.5; expClause1(:,2:end,:) = false; resultClause1 = X(expClause1); % Clause 2 expClause2 = X < 0.5; expClause2(:,:,1) = false; expClause2(:,1:2,2) = false; resultClause2 = X(expClause2); % Clause 3 expClause3 = (X > 0.25) & (X < 0.75); expClause3(1:3:end) = false; expClause3(2:3:end) = false; resultClause3 = X(expClause3);
I hope you have acquired a deeper knowledge on how logical indexing works in MATLAB. The source code developed in this tutorial is available at this page.