vectorized roots for quadratic equations
Version 1.0.0 (3.17 KB) by Stephen Becker
Finds roots for a series of quadratic equations in a vectorized manner
Updated 26 May 2023
Finds roots for a series of quadratic equations. This is basically the vectorized quadratic formula but with significant improvements to increase the numerical stability since the naive quadratic formula suffers from bad cancellation errors; see brief lecture notes and this helpful stack exchange post.
The benefit of using this over Matlab's builtin roots command is that this code is vectorized, so that you can give it many quadratic equations (one per row) and it solves them all, whereas with roots you need to loop over them in a for loop.
On my laptop, for solving a million quadratics, it takes about 7 seconds for Matlab's roots and about 0.1 seconds for my code.
Note: there are slight differences in convention from Matlab's roots for the cases when there is only 1 or 0 roots, since my code always needs to output 2 roots. This code will output a nan if there is a missing root, and output inf if any number is a root (that's only for the case a=b=c=0).
Stephen Becker (2023). vectorized roots for quadratic equations (https://www.mathworks.com/matlabcentral/fileexchange/130109-vectorized-roots-for-quadratic-equations), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with R2023a
Compatible with any release
Platform CompatibilityWindows macOS Linux
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!
Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.