Using the C++ Math Library | ![]() ![]() |
The M-File roots() Function
The C++ example_roots()
function is a translation of the M-file roots()
function. For purposes of comparison, roots.m
is reproduced below. Not counting the comments or the main routine, the C++ code is only four lines longer than the M-code. Two of the extra lines are used for declaring variables and the other two for including header files.
MATLAB M-file code for roots()
:
function r = roots(c) %ROOTSFind polynomial roots. % ROOTS(C) computes the roots of the polynomial whose % coefficients are the elements of the vector C. If C has N+1 % components, the polynomial is C(1)*X^N + ... + C(N)*X + % C(N+1). % % See also POLY. % J.N. Little 3-17-86 % Copyright (c) 1984-97 by The MathWorks, Inc. % ROOTS finds the eigenvalues of the associated companion matrix. n = size(c); if ~sum(n <= 1) error('Must be a vector.') end n = max(n); c = c(:).'; % Make sure it's a row vector % Strip leading zeros and throw away. Strip trailing zeros, % but remember them as roots at zero. inz = find(abs(c)); nnz = max(size(inz)); if nnz ~= 0 c = c(inz(1):inz(nnz)); r = zeros(n-inz(nnz),1); else r = []; end % Polynomial roots via a companion matrix n = max(size(c)); a = diag(ones(1,n-2),-1); if n > 1 a(1,:) = -c(2:n) ./ c(1); end r = [r;eig(a)];
![]() | Example Program: Rewriting roots.m in C++ (ex8.cpp) | The C++ roots() Function | ![]() |