diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7b1c517 --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +# project +bin/ +out/ +mat/ +mtx/ + +# hpc +exclude +hpc_auth_sync.sh + +# eclipse +.project +.cproject +.settings/ + +# matlab +*.m~ + diff --git a/homework_1/Exercise 1-knn-openmp.pdf b/homework_1/Exercise 1-knn-openmp.pdf new file mode 100644 index 0000000..b0c4364 Binary files /dev/null and b/homework_1/Exercise 1-knn-openmp.pdf differ diff --git a/homework_1/matlab/dist2.m b/homework_1/matlab/dist2.m new file mode 100644 index 0000000..a6451ce --- /dev/null +++ b/homework_1/matlab/dist2.m @@ -0,0 +1,18 @@ +function [D2] = dist2(X, Y) +% Calculates the squares of the distances of X and Y +% +% X: A mxd array with m d-dimentional points +% Y: A nxd array with n d-dimentional points +% d: Must be the same + + [~, d1] = size(X); + [~, d2] = size(Y); + if d1 ~= d2 + error('X,Y column dimensions must match'); + end + %D2 = sqrt((X.^2)*ones(d,m) -2*X*Y' + ones(n,d)*(Y.^2)'); + D2 = max(sum(X.^2, 2) - 2 * X*Y' + sum(Y.^2, 2)', 0); + D2 = sqrt(D2); + +end + diff --git a/homework_1/matlab/knnsearch2.m b/homework_1/matlab/knnsearch2.m new file mode 100644 index 0000000..560694d --- /dev/null +++ b/homework_1/matlab/knnsearch2.m @@ -0,0 +1,24 @@ +function [idx, dst] = knnsearch2(C, Q, k) +% C: Is a mxd matrix (Corpus) +% Q: Is a nxd matrix (Query) +% k: The number of nearest neighbors needded + + % Calculate the distance matrix between C and Q + % D is an m x n matrix where each element D(i, j) is the distance + % between the i-th point in C and the j-th point in Q. + % k is the number of nearest neighbors to find. + D = dist2(C, Q); + + % Find the k-nearest neighbors for each query point in Q + % [~,n] = size(D); + % for j = 1:n + % [dst(:, j), idx(:, j)] = mink(D(:, j), k); + % end + [dst, idx] = mink(D, k, 1); % mink along dimension 1 for each query point + + % Transpose the output to match the knnsearch format + idx = idx'; % Make idx an n x k matrix + dst = dst'; % Make dst an n x k matrix + +end + diff --git a/homework_1/matlab/test.m b/homework_1/matlab/test.m new file mode 100644 index 0000000..321d13c --- /dev/null +++ b/homework_1/matlab/test.m @@ -0,0 +1,24 @@ +% +% +% + +C = rand(40000,4); +Q = rand(4000,4); + +disp ('C-Q'); +disp ('build-in') +tic; [i1, d1] = knnsearch(C, Q, 'k', 4); toc +disp ('mine') +tic; [i2, d2] = knnsearch2(C, Q, 4); toc +sum(i1-i2) +sum(d1-d2) + +disp (' '); +disp (' '); +disp ('C-C'); +disp ('build-in') +tic; [i1, d1] = knnsearch(C, C, 'k', 4); toc +disp ('mine') +tic; [i2, d2] = knnsearch2(C, C, 4); toc +sum(i1-i2) +sum(d1-d2)