Skip to content

Instantly share code, notes, and snippets.

@zenon
Created October 18, 2011 07:09
Show Gist options
  • Save zenon/1294788 to your computer and use it in GitHub Desktop.
Save zenon/1294788 to your computer and use it in GitHub Desktop.
Compare a = pinv(A)*b and a = A\b, with timing in GNU Octave
function [ti ts delta] = solveTest(n)
% Compares a = pinv(A)*b and a = A\b, with timing.
%#####################################################%
$ Thanks to John D. Cook of
$ http://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/
$ where he mentioned that solving vs inverting is O(n^2) vs O(n^3)
$
% Results:
% solveTest(1000); =>
% 13.55s for inversion, 0.16s for A\b. Difference 0.00
%
% solveTest(1500);
% 43.69s for inversion, 0.52s for A\b. Difference 0.00
%
% solveTest(2000);
% 108.68s for inversion, 1.15s for A\b. Difference 0.00
%
% on GNU Octave, version 3.2.4 (32bit), Win 7 (64 bit)
%
% Greetings to the @ml_class team!
%#####################################################%
%initialize
A = rand(n);
b = rand(n,1);
t0 = time;
% solve with inverse
Ai = pinv(A);
a_i = Ai * b;
t1 = time;
ti = t1-t0;
% solve with A \ b
a_s = A \ b;
t2 = time;
ts = t2 - t1;
% compare
delta = sum(abs(a_i - a_s));
fprintf("%0.2fs for inversion, %0.2fs for A\\b. Difference %0.2f \n",ti,ts,delta);
[ti ts delta];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment