First matlab approach for linear implementation (V0)

This commit is contained in:
Christos Choutouridis 2024-11-10 20:15:18 +02:00
parent c0b15bcf7d
commit 1c60b502b3
5 changed files with 84 additions and 0 deletions

18
.gitignore vendored Normal file
View File

@ -0,0 +1,18 @@
# project
bin/
out/
mat/
mtx/
# hpc
exclude
hpc_auth_sync.sh
# eclipse
.project
.cproject
.settings/
# matlab
*.m~

Binary file not shown.

18
homework_1/matlab/dist2.m Normal file
View File

@ -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

View File

@ -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

24
homework_1/matlab/test.m Normal file
View File

@ -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)