3 methods are compared here:
- A simple loop through all the lines, using
rootsfor each line. - A fully loop approach based on the YBE idea of using a block-diagonal matrix, using
sparseas an intermediate - A simple loop through all the lines, but this time using the "built-in" code from
roots.
Code:
%// The polynomials
m = 15;
n = 8;
N = 1e3;
X = rand(m,n);
%// Simplest approach
tic
for mm = 1:N
R = zeros(n-1,m);
for ii = 1:m
R(:,ii) = roots(X(ii,:));
end
end
toc
%// Completely loopless approach
tic
for mm = 1:N
%// Indices for the scaled coefficients
ii = repmat(1:n-1:m*(n-1), n-1,1);
jj = 1:m*(n-1);
%// Indices for the ones
kk = bsxfun(@plus, repmat(2:n-1, m,1), (n-1)*(0:m-1).'); %'
ll = kk-1;
%// The block diagonal matrix
coefs = -bsxfun(@rdivide, X(:,2:end), X(:,1)).'; %'
one = ones(n-2,m);
C = full(sparse([ii(:); kk(:)], [jj(:); ll(:)],...
[coefs(:); one(:)]));
%// The roots
R = reshape(eig(C), n-1,m);
end
toc
%// Simple loop, roots() "inlined"
tic
R = zeros(n-1,m);
for mm = 1:N
for ii = 1:m
A = zeros(n-1);
A(1,:) = -X(ii,2:end)/X(ii,1);
A(2:n:end) = 1;
R(:,ii) = eig(A);
end
end
toc
Results:
%
Elapsed time is 0.780930 seconds. %
Elapsed time is 1.959419 seconds. %
Elapsed time is 0.326140 seconds. %
%
Elapsed time is 1.785438 seconds. %
Elapsed time is 110.1645 seconds. %
Elapsed time is 1.326355 seconds. %
, , : MATLAB : OLD. MATLAB R2009 .
, , , . : , - . , eig, N³ (, ), - (, -), .
- ^ _ ^
, , eig() , . , , /. , , . , .. , .
- , , MATLAB.
, , , , , .
, , , , - , .
, , , , . :)