Create two matrices using the following code:
A = [1, 5, 2; 3, 6, 4]; B = [true, false, false; false, true, false];
A = 1 5 2 3 6 4
B = 1 0 0 0 1 0
MATLAB supports three ways to reference elements in a matrix:
Logical indexing uses a logical matrix as index, where the position of
true values indicates the elements of interest in the matrix being accessed. So, the expression
A(B) returns the following result:
ans = 1 6
The common use of logical indexing is to reference the elements that satisfy a certain condition. In rare cases you will create the logical matrix manually.
% Elements in A greater than or equal to 3 geThree = A(A>=3);
geThree = 3 5 6 4
% Elements lower than 6 lSix = A(A<6);
lSix = 1 3 5 2 4
% Elements greater than 1 and lower than 6 rangeExp = (A > 1) & (A < 6); range = A(rangeExp);
range = 3 5 2 4
% Set to 0 elements lower than 5 A(A<5) = 0;
A = 0 5 0 0 6 0
Note: When the logical expression is large or uses logical operators, best practices suggest to write it independently in a new line.
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, but especially this tutorial.
- 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 functions
mod. Create a matrix of size 4×4 and get the elements that are:
- Greater than 5 and lower than 10
- Divisible by 2 and greater than 7
- Greater than 4, divisible by 3, and not greater than 15
Additionally set odd numbers to 0.
A possible solution could be:
doc magic; doc mod; X = magic(4); % Clause 1 expClause1 = (X > 5) & (X < 10); resultClause1 = X(expClause1); % Clause 2 expClause2 = (mod(X,2) == 0) & (X > 7); resultClause2 = X(expClause2); % Clause 3 expClause3 = (X > 4) & (mod(X,3) == 0) & (X <= 15); resultClause3 = X(expClause3); % Clause 4 expClause4 = (mod(X,2) ~= 0); X(expClause4) = 0;
I hope you have learned how to use logical indexing in MATLAB. The source code developed in this tutorial is available at this page.