function Y = cofilter(K,Y)

k = 10;
[m,n] = size(Y);

% mean user rating
mu = zeros(1, n);
for i = 1:n
    mu(i) = mean(Y(~isnan(Y(:,i)),i));
end

for i = 1:n
    % i-th user
    for j = 1:m
        % j-th instance
        if isnan(Y(j,i))
            % find users who rated j-th instance
            User = find(~isnan(Y(j,:)));
            if k > length(User)
                % sort these users
                [foo, I] = sort(K(User,i), 'descend');
                % k nearest users
                User = User(I(1:k));
            end
            simility = K(User,i)/sum(K(User,i));
            weights  = Y(j,User) - mu(User);
            Y(j,i) = min(max(mu(i) + weights * simility, -10), +10);
        end
    end
end
