max — Find maximum values by reduction or pairwise comparison.
max(A) reduces along the first non-singleton dimension and can also return indices. max(A,B) compares operands elementwise and has one output; an empty second argument selects reduction. Ordinal categorical arrays use the existing categorical extrema route before numeric admission.
Syntax
M = max(A)
[M, I] = max(A)
M = max(A, B)
M = max(A, B, nanflag)
M = max(A, [], dim)
[M, I] = max(A, [], dim)All supported max forms
M = max(A)
[M, I] = max(A)
M = max(A, B)
M = max(A, B, nanflag)
M = max(A, [], dim)
[M, I] = max(A, [], dim)
M = max(A, [], vecdim)
[M, I] = max(A, [], vecdim)
M = max(A, [], "all")
[M, I] = max(A, [], "all")
M = max(A, [], "linear")
[M, I] = max(A, [], "linear")
M = max(A, [], nanflag)
[M, I] = max(A, [], nanflag)
M = max(A, [], "ComparisonMethod", method)
[M, I] = max(A, [], "ComparisonMethod", method)
M = max(A, B, "ComparisonMethod", method)
M = max(A, [], optionName, optionValue, ...)
[M, I] = max(A, [], optionName, optionValue, ...)
M = max(A, B, optionName, optionValue, ...)Inputs
A- Type
Any- Required
- Yes
- Description
- Input scalar or array.
B- Type
Any- Required
- Yes
- Description
- Second operand for element-wise maximum.
nanflag- Type
StringScalar- Required
- No
- Default
"includenan"- Description
- Missing-value mode: "includenan" or "omitnan".
placeholder- Type
Any- Required
- No
- Default
[]- Description
- Empty placeholder selecting reduction-argument grammar.
dim- Type
Any- Required
- No
- Description
- Reduction dimension selector (scalar or dimension vector).
flag- Type
StringScalar- Required
- No
- Description
- Reduction mode flag: "all" or "linear".
optionName- Type
StringScalar- Required
- No
- Default
"ComparisonMethod"- Description
- Option name (currently "ComparisonMethod").
method- Type
StringScalar- Required
- No
- Default
"auto"- Description
- Comparison method: "auto", "abs"/"magnitude", or "real".
optionName- Type
StringScalar- Required
- Variadic
- Description
- Name-value option name.
optionValue- Type
Any- Required
- Variadic
- Description
- Name-value option value.
Returns
M- Type
Any- Description
- Maximum numeric values or ordinal categorical values.
I- Type
NumericArray- Description
- One-based maximum indices/origins.
Returned values from max depend on how many outputs the caller requests.
Errors
RunMat:max:InvalidArgument- When
- Argument grammar, dimensions, or option names/values are invalid.
- Message
max: invalid argument
RunMat:max:InvalidInput- When
- Input values cannot be converted to supported max domains.
- Message
max: invalid input
RunMat:max:SizeMismatch- When
- Element-wise operands are not broadcast-compatible.
- Message
max: size mismatch
Reduction and pairwise forms
max(A) finds each column's maximum in a matrix; a second output gives one-based indices. max(A,[],dim) chooses an axis, max(A,[],vecdim) chooses several, and all or linear selects a maximum over every element with a linear index when requested.
max(A,B) compares compatible operands elementwise using implicit expansion and has exactly one output. max(A,B,'omitnan') chooses the non-NaN side when only one operand is NaN. An empty second argument switches to reduction grammar; pairwise comparison never returns an origin index.
Reduction defaults to includenan: a slice containing NaN yields the first NaN and its index. omitnan ignores NaNs; an all-NaN slice yields NaN for both value and index.
Classes and ordering
Real integer maximum values preserve their exact input class, including wide uint64; indices are one-based doubles. Real single and double retain class. Logical values enter the numeric comparison domain and return double values.
Complex values default to magnitude ordering with phase tie-breaking. ComparisonMethod may select real, abs, or magnitude; the name-value control is decoded into a typed identity before comparison.
Ordinal categorical arrays retain categorical values and can return indices. Nonordinal or malformed categorical objects reject through the table-owned argument/variable diagnostics before numeric max admission; generic object inference remains dynamic.
GPU and compilation
The GPU/fusion floating-kernel declaration lists single and double, with reduce_max_dim and reduce_max provider hooks; the ordinary resident reduction route currently selects reduce_max_dim for admitted axes and can preserve typed integer storage when its provider supports it. Supported pairwise device operands or one device operand with an eligible scalar can use the owning pairwise provider route. The public pairwise form has one output.
Reduction omitnan, custom comparison methods, linear indexing, multi-axis selectors that lack a supported hook, and complex inputs can require a gather and host result. The selected reduction provider route checks its legal form before invoking the provider. An admitted host materialization is a residency change, not a resident result; supported resident execution is retained when its hook is available.
When shared fusion or placement selects acceleration, callers generally need not create a GPU array manually. The planner may use an admitted maximum reduction kernel and may place a later compatible kernel after a host result. Static inference stays dynamic when a second operand might be an empty reduction placeholder or a nonempty pairwise operand.
Examples
Maximum and index by column
A = [3 1 5;4 2 6];
[m,idx] = max(A)Expected output:
m = [4 2 6]; idx = [2 2 2]Maximum along rows
A = [3 1 5;4 2 6];
[m,idx] = max(A,[],2)Expected output:
m = [5;6]; idx = [3;3]Global maximum and linear index
A = reshape(1:12,[3 4]);
[m,idx] = max(A,[],'all')Expected output:
m = 12; idx = 12Ignore NaNs during reduction
values = [NaN 4 2;3 NaN 1];
[m,idx] = max(values,[],1,'omitnan')Expected output:
m = [3 4 2]; idx = [2 1 1]Pairwise maximum with implicit expansion
A = [1 4 7];
B = [2;3;5];
C = max(A,B)Expected output:
C = [2 4 7;3 4 7;5 5 7]Complex magnitude and real ordering
Z = [1+2i,2+1i,-2+2i];
M = max(Z)
R = max(Z,[],'ComparisonMethod','real')Expected output:
M = -2+2i; R = 2+1iUsing max with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how max changes the result.
Run a small max example, explain the result, then change one input and compare the output.
FAQ
How can I request a global maximum's linear index?⌄
Use [m,idx] = max(A,[],'all') or max(A,[],'linear'). The index is one-based in column-major order.
Does pairwise max return an origin index?⌄
No. max(A,B) has one output; use a reduction form for indices.
How are complex values compared?⌄
The default orders by magnitude with phase tie-breaking; ComparisonMethod can select real, abs, or magnitude.
What if all values are NaN in omitnan mode?⌄
The reduction returns NaN for both value and index in that slice.
Can pairwise max omit NaNs?⌄
Yes. max(A,B,'omitnan') chooses the non-NaN operand when exactly one is NaN.
Can I combine pairwise comparison with dimension reduction?⌄
No. max(A,B) is pairwise and has one output. Use max(A,[],dim) or max(A,[],vecdim) to reduce selected dimensions.
Do all modes run on a GPU?⌄
No. Supported provider forms stay resident; unsupported modes can gather for host execution.
Do integers lose precision in max?⌄
Real integer maxima preserve native integer class and exact comparisons, including wide values; indices are double.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var
Elementwise
abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8
Optim
acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fmincon · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
Trigonometry
acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Factor
chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. Read exactly how max is executed, line by line, in Rust.
- View the source for max in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.