find — Locate nonzero indices and values in MATLAB and RunMat.

find(X) returns indices of nonzero elements in X. With one output it returns 1-based linear indices; with multiple outputs it returns row/column subscripts (and optionally values). Count limits and search-direction options follow MATLAB semantics.

Syntax

idx = find(X)
idx = find(X, K)
idx = find(X, K, direction)
[row, col] = find(X)
[row, col] = find(X, K, direction)
[row, col, v] = find(X)
[row, col, v] = find(X, K, direction)

Inputs

NameTypeRequiredDefaultDescription
XAnyYesInput array to search.
KNumericScalarYesMaximum number of indices to return.
directionStringScalarYes"first"Direction selector: `"first"` or `"last"`.

Returns

NameTypeDescription
idxNumericArrayLinear indices of non-zero elements.
rowNumericArrayRow subscripts of non-zero elements.
colNumericArrayColumn subscripts of non-zero elements.
vAnyValues at the reported row/column locations.

Returned values from find depend on how many outputs the caller requests.

Errors

IdentifierWhenMessage
RunMat:find:InvalidInputInput type or option arguments are not valid for find.find: invalid input arguments
RunMat:find:ProviderOutputGPU provider does not return expected output buffers for requested nargout.find: provider output buffer mismatch
RunMat:find:InternalErrorInternal tensor conversion/materialization fails while building outputs.find: internal error

How find works

  • find(X) scans in column-major order and returns a column vector of linear indices.
  • find(X, K) limits the result to the first K matches; K = 0 yields an empty result.
  • find(X, K, 'first') (default) scans from the start, while 'last' scans from the end.
  • find(X, 'last') is equivalent to find(X, 1, 'last') and returns the final nonzero index.
  • [row, col] = find(X) returns per-element row and column subscripts for 2-D or N-D inputs (higher dimensions are flattened into the column index, matching MATLAB semantics).
  • [row, col, val] = find(X) also returns the corresponding values; complex inputs preserve their complex values.
  • Logical, char, integer, and double inputs are all supported. Empty inputs return empty outputs with MATLAB-compatible shapes.

Does RunMat run find on the GPU?

When the input already resides on the GPU (i.e., a gpuArray), RunMat gathers it if the active provider does not implement a dedicated find kernel, performs the computation on the host, and then uploads the results back to the provider. This preserves residency so downstream fused kernels can continue on the device without an explicit gather. Providers may implement a custom hook in the future to run find entirely on the GPU; until then, the automatic gather/upload path maintains correctness with a small one-off cost.

GPU memory and residency

Usually you do not need to move data with gpuArray manually. If a provider backs find directly, the entire operation stays on the GPU. Otherwise, RunMat gathers once, computes on the host, and then uploads results back to the active provider so subsequent kernels remain device-resident. This means GPU pipelines continue seamlessly without additional gather/gpuArray calls from user code.

Examples

Finding linear indices of nonzero elements

A = [0 4 0; 7 0 9];
k = find(A)

Expected output:

k =
     2
     4
     6

Limiting the number of matches

A = [0 3 5 0 8];
first_two = find(A, 2)

Expected output:

first_two =
     2
     3

Locating the last nonzero element

A = [1 0 0 6 0 2];
last_index = find(A, 'last')

Expected output:

last_index =
     6

Retrieving row and column subscripts

A = [0 4 0; 7 0 9];
[rows, cols] = find(A)

Expected output:

rows =
     2
     1
     2

cols =
     1
     2
     3

Capturing values alongside indices (including complex inputs)

Z = [0 1+2i; 0 0; 3-4i 0];
[r, c, v] = find(Z)

Expected output:

r =
     1
     3

c =
     1
     1

v =
   1.0000 + 2.0000i
   3.0000 - 4.0000i

Using find with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how find changes the result.

Run a small find example, explain the result, then change one input and compare the output.

FAQ

What elements does find consider nonzero?

Any element whose real or imaginary component is nonzero. For logical inputs, true maps to 1 and is considered nonzero; false is ignored.

How are higher-dimensional arrays handled when requesting row/column outputs?

find treats the first dimension as rows and flattens the remaining dimensions into the column index, matching MATLAB's column-major storage.

What happens when I request more matches than exist?

find returns all available nonzero elements—no error is raised. For example, find(A, 10) simply returns every nonzero in A if it has fewer than 10.

Does find support char arrays and integers?

Yes. Characters are converted to their numeric code points during the test for nonzero values; integers are promoted to double precision for the result vectors.

Can I run find entirely on the GPU today?

Not yet. The runtime gathers GPU inputs, computes on the host, and re-uploads results. Providers can implement the optional find hook to make the entire path GPU-native in the future.

What shapes do empty results take?

When no element matches, the returned arrays are 0×1 column vectors, just like MATLAB.

How does find interact with fusion or auto-offload?

find is a control-flow style operation, so it does not participate in fusion. Auto-offload still keeps data resident on the GPU where possible by uploading results after the host computation.

Does find preserve complex values in the third output?

Yes. When you request the value output, complex inputs return a complex column vector that matches MATLAB's behaviour.

Can I combine find with gpuArray explicitly?

Absolutely. If you call find(gpuArray(X)), the runtime ensures outputs stay on the GPU so later GPU-aware builtins can consume them without additional transfers.

Is there a way to obtain subscripts for every dimension?

Use find to get linear indices and then call ind2sub(size(X), ...) if you need explicit per-dimension subscripts for N-D arrays.

Indexing

ind2sub · sub2ind

Sorting Sets

argsort · intersect · ismember · issorted · setdiff · sort · sortrows · union · unique

Shape

cat · circshift · diag · flip · fliplr · flipud · horzcat · ipermute · kron · permute · repelem · repmat · reshape · rot90 · squeeze · tril · triu · vertcat

Creation

colon · eye · false · fill · inf · linspace · logspace · magic · meshgrid · nan · ones · peaks · rand · randi · randn · randperm · range · true · zeros

Introspection

isempty · ismatrix · isscalar · isvector · length · ndims · numel · size

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how find is executed, line by line, in Rust.

About RunMat

RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.