0
0
MATLABdata~5 mins

Logical indexing in MATLAB

Choose your learning style9 modes available
Introduction
Logical indexing helps you pick elements from a list or array by using true or false values. It makes selecting data easy and fast.
You want to find all numbers greater than 10 in a list.
You need to change only the negative numbers in an array to zero.
You want to select all rows in a table where a condition is true.
You want to count how many elements meet a certain condition.
You want to filter data without writing loops.
Syntax
MATLAB
result = array(logical_index)
The logical_index is an array of true (1) or false (0) values, same size as array.
Only elements where logical_index is true are selected.
Examples
Selects elements of A that are greater than 10.
MATLAB
A = [5, 12, 7, 20];
B = A > 10;
result = A(B);
Replaces all negative numbers in A with zero.
MATLAB
A = [3, -1, 4, -5];
A(A < 0) = 0;
Selects all even numbers from A.
MATLAB
A = [10, 15, 8, 22];
result = A(mod(A,2) == 0);
Sample Program
This program finds all elements in A that are greater than 5 and displays them.
MATLAB
A = [2, 9, 4, 7, 12];
logicalIndex = A > 5;
selectedElements = A(logicalIndex);
disp('Elements greater than 5:');
disp(selectedElements);
OutputSuccess
Important Notes
Logical indexing works only if the logical array is the same size as the original array.
You can use logical indexing to both read and write parts of an array.
It is faster and cleaner than using loops for selecting elements.
Summary
Logical indexing uses true/false arrays to pick elements from another array.
It helps filter, select, or change data easily without loops.
Make sure the logical array matches the size of the original array.