Written and maintained by CASRAI Editorial Board
Published
On this page
Quantitative empirical researchers, computational analysts, and data scientists routinely compute square roots across numerical modeling and matrix algebra workflows. In MATLAB, calculating roots involves distinct operations depending on whether an analysis requires element-by-element evaluation, strict domain checking on real values, or algebraic matrix factorization. Mastering the built-in functions sqrt, realsqrt, and sqrtm prevents subtle bugs such as silent complex contamination, operator confusion, or erroneous matrix transformations.
What it is used for in research
Square root calculations are foundational operations across scientific computing, data analysis, and quantitative research. In numerical modeling, researchers compute square roots to calculate Euclidean distances, root-mean-square errors (RMSE), signal-to-noise ratios, and standard deviations. In matrix algebra and multivariate statistics, calculating matrix roots is required for data whitening, Kalman filtering, and evaluating the Mahalanobis distance metric.
In MATLAB, square root computation is divided into three distinct built-in functions based on mathematical domain and data structures:
sqrt(Element-Wise Square Root): The general-purpose mathematical function that evaluates the square root of every element across scalars, vectors, matrices, multidimensional arrays, tables, and timetables. When an input element is negative or complex,sqrtcomputes the result over the complex plane, returning complex numbers rather than terminating execution.realsqrt(Domain-Constrained Real Square Root): A specialized function for strictly nonnegative real data. If any array element is negative or contains an imaginary component,realsqrtimmediately throws a runtime error (MATLAB:realsqrt:complexResult). This provides automated domain assertion in physical simulations where negative values signify numerical divergence or physical impossibility.sqrtm(Algebraic Matrix Square Root): A linear algebra function that computes the principal matrix square root $X$ of a square matrix $A$ such that $X times X = A$. This is distinct from element-wise roots and is applied directly to covariance matrices and linear transformation operators.
High-throughput data pipelines also leverage MATLAB vectorization to process multi-million element arrays simultaneously without iterative loops, while statistical workflows use square roots to derive dispersion metrics alongside standard deviation in MATLAB and vector norm in MATLAB calculations.
Install or access (official source only)
The sqrt, realsqrt, and sqrtm functions are core built-in components of the MATLAB environment provided directly by MathWorks. They do not require specialized toolboxes (such as the Symbolic Math Toolbox or Statistics and Machine Learning Toolbox) and are included in all standard installations:
- Local Desktop Installation: Access via the official MathWorks installer for Windows, macOS, or Linux through an institutional campus license or individual organizational license.
- MATLAB Online: Run calculations through any standard web browser via the official MathWorks cloud environment (
https://matlab.mathworks.com). - High-Performance Computing (HPC) Clusters: Accessible in batch or interactive mode on university and national laboratory compute clusters using environment modules (e.g.,
module load matlab) and executed via command line:matlab -batch "run_analysis".
Step-by-step task
Follow these numbered steps to calculate element-wise and matrix square roots in MATLAB.
-
Calculate scalar and element-wise array square roots with sqrt:
The primary method to calculate the matlab sqrt for scalars, vectors, or arrays element by element is passing the variable directly to
sqrt:% Scalar square root val = 64; res = sqrt(val); % Returns 8 % Vector element-wise square root v = [4, 9, 16, 25, 36]; v_sqrt = sqrt(v); % Returns [2, 3, 4, 5, 6] % 2D matrix element-wise square root A = [1, 4; 9, 16]; A_sqrt = sqrt(A); % Returns: % 1 2 % 3 4 -
Handle negative and complex inputs in sqrt:
When computing a square root in matlab for negative numbers,
sqrtproduces complex numbers using the imaginary unit $i$:% Negative scalar z = sqrt(-16); % Returns 0.0000 + 4.0000i % Vector containing mixed positive and negative values x = -2:2; y = sqrt(x); % Returns: % 0.0000 + 1.4142i 0.0000 + 1.0000i 0.0000 + 0.0000i 1.0000 + 0.0000i 1.4142 + 0.0000iFor any complex number $z = u + iw$, MATLAB evaluates $sqrt{z} = sqrt{r}(cos(phi/2) + isin(phi/2))$, where $r = |z|$ and $phi = text{angle}(z)$ in the interval $[-pi, pi]$.
-
Enforce real-value domain constraints using realsqrt:
In physical models (such as optical intensities, acoustic pressures, mass, or reaction rates) where negative values represent corrupted sensor noise or numerical instability, calling sqrt in matlab directly could silently introduce imaginary parts. Use
realsqrtto enforce strict validation:% Nonnegative array validation measurements = [0.25, 1.44, 9.00]; clean_roots = realsqrt(measurements); % Returns [0.5000, 1.2000, 3.0000] % Error assertion on negative input try corrupt_val = realsqrt(-4); catch ME disp(ME.identifier); % Displays 'MATLAB:realsqrt:complexResult' end -
Compute algebraic matrix square roots with sqrtm:
To execute square root matlab linear algebra operations finding a matrix $X$ such that $X^2 = A$, call
sqrtmon a square matrix. Do not usesqrt(A)for matrix equations:% Define a positive definite matrix A = [5, -4, 1; -4, 6, -4; 1, -4, 5]; % Compute the principal matrix square root X = sqrtm(A); % Verify that X * X reconstructs matrix A A_reconstructed = X * X; % Sourced residual norm and conditioning diagnostics [X_diag, resnorm] = sqrtm(A); [X_full, alpha, condest] = sqrtm(A); -
Use the element-wise power operator alternative:
Researchers can also calculate array roots using the dot-power operator (
.^). For fast vectorized calculations in sqrt matlab scripts:data = [100, 400, 900]; roots_power = data .^ 0.5; % Returns [10, 20, 30]Note that omitting the dot (
A ^ 0.5) invokes matrix power, equivalent tosqrtm(A)on square matrices, whereasA .^ 0.5computes element-wise roots equivalent tosqrt(A).
Output and how to read it
Understanding the structure and numerical precision of square root outputs prevents propagation errors in downstream code:
- Data Types and Dimensionality: Output arrays maintain the identical dimension and underlying numeric class (
doubleorsingle) of the input. Passing an integer class likeuint8(25)directly tosqrtautomatically returns adoublein standard MATLAB releases. - Complex Output Representation: Complex results display real and imaginary parts separated by a sign:
0.0000 + 3.0000i. In boolean expressions,isreal(sqrt(-1))evaluates tofalse. - Residual Norm in sqrtm: The optional output
resnormfrom[X, resnorm] = sqrtm(A)quantifies the Frobenius relative error:
$$text{resnorm} = frac{|A – X^2|_F}{|A|_F}$$
Values close to machine epsilon (approximately $10^{-16}$ for double precision) confirm an accurate square root factorization. - Condition Number and Stability: The outputs
alphaandcondestfrom[X, alpha, condest] = sqrtm(A)indicate mathematical conditioning. The residual is approximately bounded by $n cdot alpha cdot text{eps}$ and the relative error is bounded by $n cdot alpha cdot text{condest} cdot text{eps}$, where $n = max(text{size}(A))$. A very largecondestindicates that the matrix square root is sensitive to small numerical perturbations. - IEEE 754 Floating-Point Standards:
sqrt(0)evaluates to0,sqrt(Inf)evaluates toInf, andsqrt(NaN)evaluates toNaN.
Troubleshooting
When running square root operations, researchers commonly encounter these errors and edge cases:
- Error:
MATLAB:realsqrt:complexResult: Raised whenrealsqrtreceives a negative value. If small negative values arise from floating-point rounding errors (e.g., $-2.22 times 10^{-16}$), clamp the inputs usingrealsqrt(max(X, 0)). If negative values are physically legitimate, switch tosqrt(X). - Error:
MATLAB:sqrtm:nonSquareMatrix: Raised whensqrtmis called on an $M times N$ matrix where $M neq N$. The algebraic matrix square root is mathematically defined only for square matrices. If you intended element-wise computation across a rectangular array, replacesqrtm(A)withsqrt(A). - Accidental Complex Numbers Contaminating Plots and Exports: When running
sqrt(x)on experimental datasets containing unexpected negative noise, MATLAB silently creates complex numbers. Subsequent calls to functions likeplot(x, y)will plot the imaginary part against the real part rather than plotting against the x-axis, or throw errors in functions that expect purely real numbers. Audit data withany(~isreal(y))or userealsqrtto catch anomalies at their source. - Matrix Operator Confusion (
^vs.^): RunningA ^ 0.5on a non-square matrix throwsError using ^: Inputs must be a scalar and a square matrix. Ensure the dot operator is included (A .^ 0.5) when element-wise computation is intended. - Singular or Defective Matrices in
sqrtm: Matrices with eigenvalues near zero or multiple defective zero eigenvalues may not possess a square root. MATLAB prints a singularity warning. To evaluate whether the computed matrix remains usable, checkresnormvia[X, resnorm] = sqrtm(A).
Free alternatives (table)
For laboratories seeking open-source computational environments or reproducible pipelines outside commercial licenses, several free scientific platforms provide equivalent square root operations. Researchers can also consult the detailed MATLAB vs R comparison for broader ecosystem differences.
| Software Environment | Element-Wise Square Root | Algebraic Matrix Square Root | Real Domain Assertion | Licensing & Implementation Notes |
|---|---|---|---|---|
| GNU Octave | sqrt(x) |
sqrtm(A) |
realsqrt(x) |
GPL v3+; drop-in syntax compatibility with MATLAB. Employs Nicholas J. Higham’s Schur algorithm for sqrtm. |
| Python (NumPy / SciPy) | numpy.sqrt(x) |
scipy.linalg.sqrtm(A) |
Raises RuntimeWarning: invalid value and returns nan for negative floats unless complex dtype is set. |
BSD; numpy.sqrt operates element-wise over arrays; scipy.linalg.sqrtm computes matrix roots. |
| Julia | sqrt.(x) (broadcast syntax) |
sqrt(A) (from LinearAlgebra stdlib) |
Throws DomainError by default on negative real numbers; requires sqrt(complex(x)) for complex roots. |
MIT; high-performance compiled language with built-in strict real domain checking by default. |
| R | sqrt(x) |
expm::sqrtm(A) |
Returns NaN with warning("NaNs produced") for negative inputs unless converted to complex. |
GPL v2/v3; standard base statistical language; matrix square root provided by the expm package. |
FAQ
How do you calculate a square root in MATLAB?
To calculate an element-wise square root in MATLAB, call sqrt(X) on any numeric scalar, vector, or matrix. For strictly nonnegative real values where negative inputs should trigger an error, use realsqrt(X). To compute the algebraic matrix square root such that $X^2 = A$, call sqrtm(A) on a square matrix.
What is the difference between sqrt and sqrtm in MATLAB?
The sqrt function operates element by element: sqrt([4, 9; 16, 25]) returns [2, 3; 4, 5]. In contrast, sqrtm calculates the algebraic principal matrix square root such that $X times X = A$. For example, if $A = [4, 1; 2, 3]$, sqrtm(A) yields a matrix $X$ where matrix multiplication $X times X$ equals $A$.
Why does sqrt in MATLAB return complex numbers instead of NaN?
MATLAB is designed for engineering and scientific mathematics where the complex plane is fully supported. When sqrt encounters negative real numbers, it calculates the principal complex root (e.g., sqrt(-9) yields 0 + 3i). If your pipeline requires an error instead of complex values, call realsqrt(X).
Can you use the power operator instead of sqrt in MATLAB?
Yes. The element-wise power expression X .^ 0.5 produces the same numerical results as sqrt(X). However, using the matrix power operator without the dot (A ^ 0.5) computes the matrix square root equivalent to sqrtm(A) on square matrices.
What does realsqrt do in MATLAB?
The realsqrt function computes the square root of each element in an array while asserting that all elements are nonnegative real numbers. If any element is negative or complex, it aborts execution with the error MATLAB:realsqrt:complexResult.
How do you verify the accuracy of a matrix square root in MATLAB?
Call [X, resnorm] = sqrtm(A). The resnorm variable returns the relative residual norm $text{norm}(A – X^2, ‘fro’) / text{norm}(A, ‘fro’)$. A value close to machine precision ($10^{-16}$) confirms that $X^2$ accurately reproduces matrix $A$.
Sources (official docs)
- MathWorks. (2026). sqrt: Square root of array elements. MathWorks MATLAB Documentation. Retrieved November 9, 2026, from https://www.mathworks.com/help/matlab/ref/sqrt.html (verified via Northwestern University mirror: http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/sqrt.html)
- MathWorks. (2026). sqrtm: Matrix square root. MathWorks MATLAB Documentation. Retrieved November 9, 2026, from https://www.mathworks.com/help/matlab/ref/sqrtm.html (verified via Northwestern University mirror: http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/sqrtm.html)
- MathWorks. (2026). realsqrt: Square root for nonnegative real arrays. MathWorks MATLAB Documentation. Retrieved November 9, 2026, from https://www.mathworks.com/help/matlab/ref/realsqrt.html (verified via Northwestern University mirror: http://www.ece.northwestern.edu/local-apps/matlabhelp/techdoc/ref/realsqrt.html)
- GNU Octave. (2026). Exponents and Logarithms: sqrt, realsqrt, nthroot. GNU Octave Documentation. Retrieved November 9, 2026, from https://docs.octave.org/latest/Exponents-and-Logarithms.html
- GNU Octave. (2026). Functions of a Matrix: sqrtm. GNU Octave Documentation. Retrieved November 9, 2026, from https://docs.octave.org/latest/Functions-of-a-Matrix.html







