MATLAB: Place values in a matrix according to indices

bsxfunindexing from a list of valuesMATLABnearest neighbor weight matrix

Hello Everyone,
I have the following code that calculates the m nearest neighbors using bsxfun:
if true
clear all
X = randn(1,5); % Random coordinates Y = randn(1,5); % Random coordinates
n = size(X,2);
m = 3; % Number of neighbors
xd = bsxfun(@minus,X(1,:)',X); yd = bsxfun(@minus,Y(1,:)',Y);
dist = (xd.^2)+(yd.^2); % Calculate distance
[xds,xind] = sort(dist,2); % Sort distances
nnlist = xind(:,2:m+1); % List of indices
w = zeros(n);
for i=1:n w(i,nnlist(i,:))=1/m; end end
The code calculates the distances and produces a list of nearest neighbor locations as follows:
nnlist =
5 2 3
3 5 4
4 2 5
3 2 5
1 2 3
The nnlist matrix is n x m or the number of locations by the number of nearest neighbors. For example, the first location (i.e nnlist(1,:)) indicates that the first observation has locations 5,2, and 3 as the nearest neighbors.
I'd like to be able to replace the values in my w matrix with a scalar value 1/m based on these indices. For example, the first row of w (which is a 5 x 5 matrix of zeros) should have a scalar value placed in locations (1,5), (1,2), and (1,3). This pattern should follow along all the rows of nnlist until all values are assigned.
The for loop does work but it is awfully slow for larger problems and I was wondering if there was a more efficient solution.
Any help would be greatly appreciated. Thank you.

Best Answer

ii=repmat((1:size(nnlist,1))',1,size(nnlist,2))
idx=sub2ind(size(w),ii,nnlist)
w(idx)=1/m