03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.11. REAL-WORLD EXAMPLE: MATRIX INVERSION 57<br />

<strong>for</strong> (unsigned k= 0; k < n; ++k) {<br />

}<br />

In each iteration we need the k-th unit vector.<br />

dense vector e k(n);<br />

<strong>for</strong> (unsigned i= 0; i < n; ++i)<br />

if (i == k)<br />

e k[i]= 1.0;<br />

else<br />

e k[i]= 0.0;<br />

The triangular solver returns a column vector. We could assign the entries of this vector directly<br />

to entries of the target matrix:<br />

<strong>for</strong> (unsigned i= 0; i < n; ++i)<br />

Inv[i][k]= upper trisolve(A, e k)[i];<br />

This is nicely short but we would compute upper trisolve n times! Although we said that per<strong>for</strong>mance<br />

is not our primary goal at this point, the raise of overall complexity from order 3 to 4 is<br />

too much waste of resources. There<strong>for</strong>e, we better store the vector and copy the entries from<br />

there.<br />

dense vector res k(n);<br />

res k= upper trisolve(A, e k);<br />

<strong>for</strong> (unsigned i= 0; i < n; ++i)<br />

Inv[i][k]= res k[i];<br />

Return our temporary matrix finishes the function that we now give in its complete <strong>for</strong>m.<br />

dense2D inverse upper(dense2D const& A)<br />

{<br />

const unsigned n= num rows(A);<br />

assert(num cols(A) == n); // Matrix must be square<br />

}<br />

dense2D Inv(n, n);<br />

<strong>for</strong> (unsigned k= 0; k < n; ++k) {<br />

dense vector e k(n);<br />

<strong>for</strong> (unsigned i= 0; i < n; ++i)<br />

if (i == k)<br />

e k[i]= 1.0;<br />

else<br />

e k[i]= 0.0;<br />

dense vector res k(n);<br />

res k= upper trisolve(A, e k);<br />

<strong>for</strong> (unsigned i= 0; i < n; ++i)<br />

Inv[i][k]= res k[i];<br />

}<br />

return Inv;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!