Written and maintained by CASRAI Editorial Board
Published
On this page
The find command in MATLAB locates the indices and values of non-zero elements or array elements meeting specific logical conditions. Researchers use find to identify event timestamps, locate threshold exceedances in experimental measurements, and extract coordinate subscripts from multi-dimensional datasets.
What it is used for in research
In quantitative scientific research and engineering, datasets frequently arrive as multi-dimensional matrices containing sensor streams, simulation meshes, or image arrays. The find function provides a direct method for identifying which elements satisfy specific mathematical or physical criteria.
Common research applications include:
- Time-series event detection: Pinpointing exact time indices where experimental measurements exceed baseline thresholds, such as spike detection in electrophysiology or load threshold exceedances in structural sensors.
- Sparse matrix analysis: Extracting row, column, and nonzero value tuples to construct or manipulate sparse matrices in computational physics, finite element methods, and network graph models.
- Region-of-interest segmentation: Isolating spatial coordinates meeting intensity, temperature, or density criteria across 2D image matrices or spatial observation grids.
- Selective data filtering: Isolating specific data subsets before performing mathematical operations, such as computing polynomial evaluations with polyval in MATLAB or setting up parameter arrays for simulation workflows.
While find is versatile, modern scientific programming in MATLAB distinguishes between operations that genuinely require integer subscript locations and operations where direct logical indexing provides superior execution speed and lower memory usage.
Install or access
The find command is a built-in core function of MATLAB provided by MathWorks and requires no additional toolboxes or package installations. Researchers typically access MATLAB through one of three institutional pathways:
- MathWorks Campus-Wide License: Academic and research institutions commonly provide Total Academic Headroom (TAH) licenses. Researchers log in with their institutional credentials at the MathWorks portal to download and activate the desktop application across Linux, macOS, or Windows workstations.
- MATLAB Online: Researchers can run MATLAB within modern web browsers without local installation. Computations execute in cloud containers, providing access to file storage and standard toolboxes.
- High-Performance Computing (HPC) Clusters: Central computing facilities host MATLAB installations licensed via network license managers (FlexLM). Researchers load the environment within terminal sessions or batch job scripts (for example, using environment module commands such as
module load matlab).
To inspect function syntax, options, and installed release details directly from the MATLAB command prompt, researchers use the help system described in our guide to the MATLAB doc command by typing doc find or help find.
Step-by-step task
The following task demonstrates how to search arrays, extract row and column subscripts, and limit search results using the find command in MATLAB.
Step 1: Define an experimental data matrix
Open the MATLAB Command Window or Editor. Create a sample matrix representing sensor readings across three experimental trials and four time points, including zero-valued baseline intervals:
% Sensor readings across 3 channels (rows) and 4 sample points (columns)
sensor_data = [
0.0, 12.4, 0.0, 8.1;
5.3, 0.0, 15.8, 0.0;
0.0, 0.0, 9.2, 11.5
];
Step 2: Locate non-zero linear indices
Execute find with a single output argument to retrieve the linear indices of all non-zero entries:
k = find(sensor_data);
MATLAB stores arrays in column-major order. The returned vector k lists the sequential linear positions of non-zero entries, traversing down columns first.
Step 3: Find elements satisfying a relational condition
Combine find with relational operators (such as >, <, ==, or ~=) to find values exceeding an experimental threshold:
threshold = 10.0;
exceed_idx = find(sensor_data > threshold);
The relational expression sensor_data > threshold produces a logical array of zeros and ones; find then returns the index positions where the condition evaluates to true.
Step 4: Extract two-dimensional row and column coordinates
Request two output arguments to determine the exact matrix coordinates (channel and sample number) for each detected reading:
[channel, sample] = find(sensor_data > threshold);
Each paired entry (channel(i), sample(i)) corresponds to one measurement meeting the threshold.
Step 5: Extract row, column, and values simultaneously
Request three outputs to capture the subscripts alongside the actual non-zero measurement values in a single call:
[r, c, vals] = find(sensor_data > threshold);
Step 6: Restrict the number of returned indices
Specify the optional integer parameter n to return only the first or last occurrences. This is useful when identifying the onset time of a signal:
% Find the first 2 occurrences
first_two = find(sensor_data > threshold, 2, 'first');
% Find the last occurrence
last_one = find(sensor_data > threshold, 1, 'last');
Output and how to read it
Understanding the structure of values returned by find ensures safe integration into automated research analysis pipelines.
- Linear Index Vectors: When called with one output (
k = find(X)), the output orientation mirrors vectors (returning a row vector ifXis a row vector, or a column vector otherwise). For 2D matrices and N-D arrays,kis always returned as a column vector. In column-major order, element(row, col)in matrix of size[M, N]maps to linear index(col - 1) * M + row. - Coordinate Arrays: When called as
[row, col] = find(X), both returned vectors share the same length. For example, ifrow = [2; 1]andcol = [1; 3], the detected elements reside at matrix positions(2, 1)and(1, 3). - Empty Outputs: If no elements satisfy the query,
findreturns an empty array of size0x1(or0x0). Downstream functions attempting direct scalar indexing on an unverified output will encounter index errors. Test empty results usingisempty(k)before indexing. - Mathematical Transformations: Extracted coordinate arrays frequently feed linear algebra routines, such as specialized solvers or MATLAB matrix inversion techniques, as well as analytical transforms like those explored in our MATLAB ilaplace guide.
Troubleshooting
Researchers encountering performance bottlenecks or script errors with find can address common issues through established programming idioms:
Issue 1: Redundant array allocation in conditional branches
Symptom: Using if ~isempty(find(data > threshold)) creates unnecessary memory allocations, which slows down iterative loops.
Solution: Replace with if any(data > threshold). The any function short-circuits upon detecting the first true element without allocating an index vector.
Issue 2: Using find when logical indexing suffices
Symptom: Writing idx = find(A > 0); A(idx) = 0; incurs the overhead of converting boolean masks into integer index arrays.
Solution: Apply logical indexing directly: A(A > 0) = 0;. Direct logical indexing runs faster and consumes less memory.
Issue 3: Subscript flattening in N-dimensional arrays
Symptom: Calling [r, c] = find(A) on a 3D or 4D array yields unexpected column coordinates because the second output flattens all trailing dimensions.
Solution: For arrays with three or more dimensions, retrieve the linear indices first and convert them with ind2sub:
lin_idx = find(A > threshold);
[dim1, dim2, dim3] = ind2sub(size(A), lin_idx);
Issue 4: Floating-point precision mismatch
Symptom: Searching for exact decimal equality using find(X == 0.3) returns empty due to standard IEEE 754 binary floating-point representation.
Solution: Apply an absolute tolerance interval: find(abs(X - 0.3) < 1e-9).
Free alternatives
Researchers working in open-source computational environments or transitioning between programming languages can perform equivalent index lookup operations using the following tools:
| Environment | Function Syntax | Indexing Base | Output Format & Characteristics |
|---|---|---|---|
| GNU Octave | find(X), [i, j, v] = find(...) |
1-based | Direct drop-in compatibility with MATLAB. Returns linear indices or coordinate vectors in column-major order under the GNU General Public License. |
| Python (NumPy) | numpy.nonzero(arr) or numpy.where(cond) |
0-based | Returns a tuple of 1D arrays containing 0-based coordinate indices along each axis. For slicing and selection mechanics, see our guide on indexing in NumPy. |
| Julia | findall(predicate, arr) |
1-based | Returns a vector of 1-based linear indices or CartesianIndex coordinate objects matching the boolean condition. Native JIT compilation ensures high loop performance. |
| R | which(x) or which(x, arr.ind = TRUE) |
1-based | Returns integer vectors of matching indices. Setting arr.ind = TRUE returns an integer matrix of row and column coordinates. |
FAQ
What is the difference between the find command in MATLAB and logical indexing?
The find command evaluates an array or logical condition and converts true positions into explicit integer index numbers (e.g. [2, 5, 8]). In contrast, logical indexing uses an array of boolean flags (true and false) directly to mask or filter elements (e.g. A(A > 5)). Logical indexing is generally faster and uses less memory unless explicit coordinate numbers or positions are required for downstream algorithms.
How do I find the first or last occurrence of a value in MATLAB?
To find the first occurrence, supply an element count limit: idx = find(X == target, 1, 'first'). To find the last occurrence, pass the direction argument: idx = find(X == target, 1, 'last'). Both forms terminate early once the requested number of matching entries is located.
What does the find command return if no elements match the condition?
When no elements satisfy the query, find returns an empty array ([]) with dimension 0x1 for vectors or matrices. To prevent index bounds errors when querying single elements, test the output using isempty(idx) before accessing elements.
Can the find command return row and column indices for 3D or multi-dimensional arrays?
When [row, col] = find(A) is called on an array with more than two dimensions, MATLAB flattens all dimensions beyond the first into the col variable. To obtain exact multi-dimensional subscripts, extract linear indices using idx = find(A) and pass them to ind2sub(size(A), idx).
Why should I use any() instead of find() in an if statement?
Using if any(condition) is more efficient than if ~isempty(find(condition)) because any short-circuits as soon as it encounters the first matching element. In contrast, find scans the entire array, allocates memory to build an index vector, and checks whether that vector is empty.
Sources
- MathWorks. find: Find indices and values of nonzero elements. MATLAB Function Reference. Accessed November 9, 2026. https://www.mathworks.com/help/matlab/ref/find.html
- GNU Octave. Finding Elements and Checking Conditions (Version 9.1.0). GNU Octave Manual. Accessed November 9, 2026. https://docs.octave.org/v9.1.0/Finding-Elements-and-Checking-Conditions.html
- Northwestern University Department of Electrical and Computer Engineering. MATLAB Function Reference: find. Academic Documentation Mirror. Accessed November 9, 2026. http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/find.html







