1

假设我们有一个向量v = [NaN NaN 1 2 3 4 NaN NaN NaN 4 5 6],我们想找到每个连续块中数字的平均值,而不是NaN。在 MATLAB 中执行此操作的有效方法是什么?(当然,实际的向量比这个例子大得多。)

4

2 回答 2

4

这是一个不需要图像处理工具箱的矢量化解决方案。

假设您的输入稍微复杂一些(我包括了一个边缘案例):

v = [NaN NaN 1 2 3 4 NaN NaN NaN 4 5 6 NaN 3 NaN 3 4]

% Index non NaNs
nonNaN      = ~isnan(v(:));

% Find the beginning of a sequence and the element after the end
subs        = diff([0; nonNaN]);
start       = subs == 1;
ends        = subs == -1;
% Start labeling sequences progressively
subs(start) = 1:nnz(start);
subs(ends)  = -(1:nnz(ends));
% Expand the labeling 
subs        = cumsum(subs);

% Use accumarray
accumarray(subs(nonNaN), v(nonNaN),[],@mean)
于 2013-05-02T00:28:00.827 回答
1

你可以看看这是否足够有效:

b=bwlabel(isfinite(v));
m=zeros(1,max(b));
for n=1:max(b)
   id=find(b==n);
   m(n)=mean(v(id));
end

令人惊讶的是,对于长向量v,我发现这比逻辑索引选项更有效mean(v(b==n))......

于 2013-05-01T23:21:24.290 回答