matlab如何用最近的邻居替换列表中的数字

时间:2015-02-13 16:11:36

标签: arrays matlab

我在matlab中有一个很长的列表(数组)。

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

我想用最接近的正值替换-1 s。

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

这样做的有效方法是什么?

2 个答案:

答案 0 :(得分:4)

我假设您要用最接近的非负值替换负值

可以使用interp1'nearest'选项{{3}}完成此操作(感谢后者的@rayryeng):

'extrap'

答案 1 :(得分:3)

假设A是输入数组,您可以使用基于 bsxfun + min 的方法 -

%// 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))