function Y = cofilter(K,Y)

k = 10;
n = size(Y,2);

% 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 = find(isnan(Y(:,i))')
        % j-th instance (not rated by user i)
        User = find(~isnan(Y(j,:)));
        if length(User) > k
            % sort these users
            [~,I] = sort(K(User,i), 'descend');
            % k nearest users
            User = User(I(1:k));
        end
        if isempty(User)
            % instance j wasn't rated; use user i's mean rating
            Y(j,i) = mu(i);
        else
            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
