Written and maintained by CASRAI Editorial Board
Published
On this page
The max command in MATLAB, invoked via the built-in max() function, computes the largest elements of vectors, matrices, and multidimensional arrays, or performs element-by-element comparisons between two datasets. In scientific data processing, experimental sensor analysis, and numerical modeling, determining extrema is a core operation for peak detection, dynamic range normalization, and signal thresholding. Because MATLAB distinguishes between dimensional reduction (finding the maximum value across dimensions) and pairwise element comparison, understanding its syntactical structures ensures accurate computation and prevents common index errors.
What it is used for in research
Researchers across biomedical engineering, neuroscience, physics, and econometric modeling utilize array extrema to evaluate physical bounds, locate event triggers, and normalize observation matrices. When analyzing multi-channel telemetry or sensor grids, computing peak values enables researchers to establish baseline thresholds, filter out sub-threshold background noise, and verify that measurements remain within instrument calibration limits.
Representative research applications of the max() command include:
- Electrophysiological Signal Analysis: Identifying cardiac R-peaks in electrocardiograms (ECG) or spike action potentials in extracellular neuronal recordings by extracting both the peak amplitude and the precise sampling timestamp.
- Volumetric Imaging and Microscopy: Scanning three-dimensional confocal microscopy stacks or MRI voxel arrays to pinpoint maximum fluorescence intensities and establish signal-to-noise ratios. Constructing such structures frequently relies on foundational matrix in MATLAB representations.
- Dynamic Normalization in Neural Networks: Scaling input feature matrices to the range [0, 1] prior to model training by dividing data vectors by their global extrema, ensuring computational reproducibility across training batches.
- Climate and Environmental Grid Modeling: Calculating monthly surface temperature maxima across longitude-latitude-altitude arrays without requiring slow nested iterative loops, optimizing processing speed through MATLAB vectorize strategies.
Install or access (official source only)
The max() command is an intrinsic, built-in function of core MATLAB and does not require supplementary toolboxes such as the Statistics and Machine Learning Toolbox or the Signal Processing Toolbox. It is immediately available in standard desktop installations and cloud environments.
To access MATLAB officially:
- MathWorks Account and Desktop Installation: Download the official MathWorks installer from the MathWorks website (mathworks.com) using an institutional, enterprise, or individual license. During installation, select base MATLAB.
- MATLAB Online: Access the cloud-hosted environment via web browser at
matlab.mathworks.comusing authorized MathWorks credentials. - Verification: Confirm that your MATLAB environment is active and functional by opening the Command Window and executing:
verThis prints your current MATLAB release version (such as R2024b or R2026a) and confirms base system availability.
Step-by-step task (numbered, with menu names or commands exactly as in the current docs)
Follow these numbered steps to execute dimensional reductions, index retrievals, multidimensional tensor operations, and pairwise array comparisons.
1. Find the Maximum Value of a One-Dimensional Vector
For a row or column vector, max(A) reduces the elements into a single scalar representing the largest numeric value:
% Define a 1D vector of sensor voltage measurements
voltage = [1.24, 3.85, 2.11, 4.92, 0.78];
% Calculate maximum scalar value
peak_voltage = max(voltage);
% Returns: peak_voltage = 4.92
2. Retrieve Both Peak Values and Their Index Locations
To record both the maximum value and the exact element coordinate where it occurs, request two output arguments: [M, I] = max(A). If the maximum value occurs multiple times, MATLAB returns the index corresponding to the first occurrence:
% Extract maximum value M and its index I
[max_val, max_idx] = max(voltage);
% Returns: max_val = 4.92, max_idx = 4
% Access the value directly through array indexing
assert(voltage(max_idx) == max_val);
Detailed rules for single-subscript and linear addressing are covered in our guide on MATLAB indexing.
3. Compute Extrema Along Matrix Columns and Rows
For a two-dimensional matrix, MATLAB operates along the first non-singleton dimension by default (dimension 1, down columns), returning a row vector of column maxima. To operate along rows (dimension 2), provide the dimension argument alongside an empty matrix [] placeholder:
% Create a 3x3 experimental matrix
A = [10, 25, 3;
4, 18, 29;
12, 6, 15];
% Default operation: maximum along columns (dim = 1)
col_max = max(A);
% Returns: [12, 25, 29]
% Explicit row operation: maximum along rows (dim = 2)
row_max = max(A, [], 2);
% Returns a 3x1 column vector: [25; 29; 15]
Critical Syntax Note: The empty array [] as the second argument is mandatory when specifying the dimension. Without [], writing max(A, 2) instructs MATLAB to perform an element-wise pairwise comparison between matrix A and the scalar integer 2.
4. Compute Extrema Across Multidimensional Arrays (R2018b+)
In modern MATLAB releases, you can find the global maximum across all elements of an N-dimensional array without flattening or reshaping via MATLAB reshape. Pass the "all" specifier:
% Generate a 3D volumetric matrix (e.g., 4x4x3 grid)
volume_data = rand(4, 4, 3);
% Global maximum across all elements in the entire array
global_peak = max(volume_data, [], "all");
% Retrieve both global peak and its linear index
[peak_val, lin_idx] = max(volume_data, [], "all", "linear");
% Convert linear index to 3D matrix subscripts
[row_sub, col_sub, page_sub] = ind2sub(size(volume_data), lin_idx);
To reduce across specific subsets of dimensions simultaneously (such as finding the maximum for each spatial slice across time), supply a vector of dimensions:
% Reduce across dimensions 1 and 2, preserving dimension 3
slice_max = max(volume_data, [], [1, 2]);
5. Perform Element-Wise Comparison Between Two Datasets
When passed two input arguments of compatible dimensions, max(A, B) evaluates elements pairwise and returns an array containing the maximum value from either dataset at each corresponding position. This leverages MATLAB implicit expansion:
baseline = [2.0, 5.0, 1.0];
threshold = [3.0, 4.0, 1.5];
% Pairwise maximum
clipped = max(baseline, threshold);
% Returns: [3.0, 5.0, 1.5]
% Thresholding an array from below with a scalar
bounded = max(baseline, 3.0);
% Returns: [3.0, 5.0, 3.0]
6. Handle Missing Data (NaN) Explicitly
Real-world experimental recordings often contain missing entries represented by NaN (Not-a-Number). By default, MATLAB’s max() function omits missing values ("omitnan" / "omitmissing"). If your research protocol requires flagging contaminated windows, specify "includenan":
noisy_sensor = [14.2, NaN, 18.9, 12.1];
% Default behavior: ignores NaN
clean_max = max(noisy_sensor); % Returns 18.9
clean_max_explicit = max(noisy_sensor, [], "omitnan"); % Returns 18.9
% Strict validation: propagates NaN if any missing value exists
flagged_max = max(noisy_sensor, [], "includenan"); % Returns NaN
Output and how to read it
The structure and dimensional format of MATLAB’s max() output depend strictly on the input array dimensions and the specified options:
- Scalar Outputs: When applied to a 1D vector or when using the
"all"specifier on multi-dimensional data,max()returns a single scalar value of the same numerical class (e.g.,double,single,int32). - Reduced Matrix Outputs: Applying
max(A, [], 1)yields a 1-by-N row vector of column maxima. Applyingmax(A, [], 2)yields an M-by-1 column vector of row maxima. The operating dimension is contracted to length 1. - Index Vector Outputs: In the two-output syntax
[M, I] = max(A, [], dim), arrayIcontains integer indices. When operating along dimension 1,I(j)represents the row index containing the maximum value of columnj. When operating along dimension 2,I(k)indicates the column index containing the maximum value of rowk. - Complex Number Ordering: When evaluated on complex numbers, MATLAB sorts elements by magnitude (modulus √(Re² + Im²)). If two complex numbers have identical magnitude, MATLAB resolves the tie by ordering according to phase angle in the interval (-π, π].
Troubleshooting
When working with array extrema in research code, watch for these common syntax pitfalls and structural conflicts:
- Accidental Pairwise Comparison Instead of Row Reduction: Calling
max(A, 2)instead ofmax(A, [], 2). Because the second argument is a scalar rather than an empty array, MATLAB executes pairwise comparison against the number 2. Fix: Always supply the second parameter as[]when passing a dimension index. - Unintended 1D Row Vector from 2D Matrix: A user expecting a single global maximum runs
max(A)on a 2D matrix, receiving a row vector of column maximums. Fix: Usemax(A, [], "all")ormax(A(:))to evaluate all elements globally. - Tied Maximums Returning Only the First Occurrence: If a signal reaches its peak at multiple sample points,
[M, I] = max(signal)returns only the first index. Fix: To extract all peak positions, combinemax()with logical indexing:all_peak_indices = find(signal == max(signal));. - Dimension Mismatch in Pairwise Comparisons: When executing
max(A, B), an error stating “Arrays have incompatible sizes for this operation” occurs if dimensions cannot be reconciled through implicit expansion. Fix: Checksize(A)andsize(B)and apply array transpose or reshaping where appropriate.
Free alternatives (table)
For scientific reproducibility, researchers often validate MATLAB analysis scripts against open-source numerical libraries. The table below outlines syntax differences for array reduction, pairwise comparison, and missing-data handling across major analytical platforms.
| Software / Library | License | Array Reduction Syntax | Pairwise Element Syntax | Missing Data (NaN) Handling |
|---|---|---|---|---|
| MATLAB | Proprietary | max(A, [], dim) / max(A, [], "all") |
max(A, B) |
"omitnan" (default) / "includenan" |
| GNU Octave | GPLv3+ | max(x, [], dim) |
max(x, y) |
Built-in NaN omission or custom NaN flags |
| Python (NumPy) | BSD 3-Clause | numpy.amax(a, axis=...) |
numpy.maximum(x1, x2) |
Propagates NaN by default; use numpy.nanmax() |
| R (base) | GPLv2 / GPLv3 | max(..., na.rm=TRUE) |
pmax(..., na.rm=TRUE) |
Returns NA by default; requires na.rm=TRUE |
| Julia | MIT | maximum(A, dims=...) |
max.(A, B) |
Propagates NaN; requires skipmissing() |
For a detailed breakdown of environment capabilities, refer to our comparison between MATLAB vs R in statistical workflows.
FAQ
How do I find the maximum value in an entire 2D matrix in MATLAB?
To find the single largest value across an entire 2D matrix, use the "all" flag: global_max = max(A, [], "all");. In versions prior to R2018b, achieve the same result by linearizing the array with the colon operator: global_max = max(A(:));.
Why does max(A, 2) not return the maximum of each row in MATLAB?
In MATLAB, the second argument of max is reserved for pairwise array comparison. Calling max(A, 2) compares each element of A against the number 2. To specify row-wise reduction along dimension 2, you must provide an empty array as the second argument: max(A, [], 2).
How do I get the row and column coordinates of the maximum matrix element?
First extract the linear index of the maximum value using [~, lin_idx] = max(A, [], "all", "linear");, then convert it into two-dimensional subscripts using [row, col] = ind2sub(size(A), lin_idx);.
Does MATLAB max() ignore NaN values by default?
Yes. In standard MATLAB operations, max() defaults to "omitnan", returning the maximum of all valid numeric elements. If your analysis requires returning NaN whenever a missing value is present, pass the flag "includenan".
What does max() return if an array contains complex numbers?
For complex inputs, MATLAB determines the maximum based on magnitude (absolute value √(Re² + Im²)). If multiple complex values have identical magnitudes, MATLAB resolves the tie by comparing their phase angles in (-π, π].
Sources (official docs)
- MathWorks. MATLAB Function Reference: max (Maximum elements of an array). URL: https://www.mathworks.com/help/matlab/ref/max.html (checked 2026-11-11).
- GNU Octave. GNU Octave Manual: Section 17.1 Minima and Maxima (max). URL: https://docs.octave.org/latest/Minima-and-Maxima.html (checked 2026-11-11).
- NumPy Developers. NumPy Reference: numpy.amax and numpy.maximum. URLs: https://numpy.org/doc/stable/reference/generated/numpy.amax.html and https://numpy.org/doc/stable/reference/generated/numpy.maximum.html (checked 2026-11-11).
- The R Project for Statistical Computing. R Documentation: Extremes (max and pmax). URL: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Extremes.html (checked 2026-11-11).
- Julia Language Documentation. Julia Base Manual: Collections and Data Structures (maximum and max). URL: https://docs.julialang.org/en/v1/base/collections/#Base.maximum (checked 2026-11-11).







