Attachment 'Aufgabe1.m'
Download 1 function [ D1, D2, td ] = Aufgabe1(X)
2 %Aufgabe1 - compute distance matrix.
3 %
4 %usage
5 % [D1, D2, td] = Aufgabe1(X)
6 %
7 %input
8 % X : (d,n)-matrix of column vectors.
9 %
10 %output
11 % D1 : (n,n)-matrix of L_2 distances, computed by for-loop.
12 % D2 : (n,n)-matrix of L_2 distances, computed by matrix algebra.
13 % td : run-time difference between computation of D1 and D2
14 %
15 %description
16 % Aufgabe1 computes the pairwise L_2 distances between the column vectors
17 % of X using two different algorithms: D1 by explicit for-loops, D2 by matrix
18 % algebra. td reports the difference in runtime between the two implementations, where
19 % td is positive, if the first method (D1) took longer than the second.
20 %
21 %author
22 % buenau@cs.tu-berlin.de
23
24 [d, n] = size(X);
25
26 % Speicher für Distanzmatrizen reservieren.
27 D1 = zeros(n, n);
28 D2 = zeros(n, n);
29
30 % Timer starten.
31 tic;
32
33 % Distanzmatrix mit for-Schleifen berechnen.
34 for j = 2:n
35 for i = 1:j-1 % Nur obere Dreiecksmatrix berechnen, da die Distanzmatrix symmetrisch ist.
36 D1(i, j) = sqrt( sum ( ( X(:,i) - X(:,j) ) .^ 2 ) );
37 end
38 end
39 D1 = D1 + D1'; % Untere Dreiecksmatrix hinzufügen.
40
41 % Timer stoppen.
42 time_D1 = toc;
43
44 % Timer starten.
45 tic;
46
47 % Distanzmatrix ohne for-Schleifen berechnen.
48 xx = sum(X .^ 2, 1); % (1, n)-Vektor der quadratischen Terme x'*x.
49 xy = X'*X; % (n, n)-Matrix der gemischten Terme x'*y.
50 D2 = sqrt(repmat(xx, [n 1]) - 2*xy + repmat(xx', [1 n]));
51
52 % Timer stoppen.
53 time_D2 = toc;
54
55 % Zeitdifferenz errechnen.
56 td = time_D1 - time_D2;
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.