user570593
user570593

Reputation: 3510

matlab how to replace a number in the list by its nearest neighbour

I have a long list (array) in matlab.

              -1, -1, -1, -1, 1, 1, -1, -1, 2, 2, 2

I want to replace the -1 s by its nearest positive values.

               1, 1,  1,  1,  1, 1, 1, 2,  2,  2, 2

What is the effective way to do this?

Upvotes: 0

Views: 83

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

I'm assuming you want to replace the negative values with the nearest non-negative values.

This can be done with interp1 with the 'nearest' and 'extrap' options (thanks to @rayryeng for the latter):

x = [1, -1, -1, -1, 1, 1, -1, -1, 2, 2, 2];
ind = x<0;
xi = interp1(find(~ind),x(~ind),find(ind),'nearest','extrap');
x(ind) = xi;

Upvotes: 4

Divakar
Divakar

Reputation: 221504

Assuming A to be the input array, you can use a bsxfun + min based approach -

%// Locations of A with -1 and positive valued locations
p1 = find(A==-1)
p2 = find(A>=0)

%// Find the indices of minimum distance locations for each element 
%// with -1 to the closest positive valued elements
[~,min_idx] = min(abs(bsxfun(@minus,p1(:).',p2(:))),[],1) %//'
%// OR [~,min_idx] = min(pdist2(p1(:),p2(:)),[],2)

%// Set -1 valued A's elements with elements located at min_idx 
%// in positive valued array
A(p1) = A(p2(min_idx))

Upvotes: 3

Related Questions