假设我们有一个向量v = [NaN NaN 1 2 3 4 NaN NaN NaN 4 5 6]
,我们希望找到每个连续块中不是NaN
的数字的平均值。在MATLAB中这样做的有效方法是什么? (当然,实际的矢量比这个例子大得多。)
答案 0 :(得分: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)
答案 1 :(得分: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))
更有效...