我在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
这样做的有效方法是什么?
答案 0 :(得分:4)
答案 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))