2011-03-10 65 views

回答

2

你可以做一个阵列相同的形状,包含X列方向是指:

means = repmat(mean(X), [size(X,1) 1]); 
X(X==0) = means(X==0); 

[编辑追加...]

或者,如果阵列冒犯的明确扩张你,你可以这样做:

X = bsxfun(@(x,y)(x+(x==0)*y), X, mean(X)); 

这是对我的口味有点太“聪明”,但似乎是约25%的速度在我测试的一个案例(1000×1000阵列,约10%是零)。

+0

我喜欢第二个! – ptikobj 2011-03-10 18:39:14

+0

然而,应用第二个产生:“???下标索引必须是真正的正整数或逻辑。”可能是因为手段(X)? – ptikobj 2011-03-10 18:45:37

+0

糟糕。我的意思是“mean(X)”,而不是“means(X)”。将编辑,道歉的方式,将废话你的评论:-)。 – 2011-03-10 19:07:34

3

这是一个矢量化解决方案,它比使用BSXFUN更快,并且不需要复制列方法数组。它只是找到对应的列索引的修改每一个线性指标,然后使用该索引,以获得正确的列均值:

colMeans = mean(X); %# Get the column means 
index = find(X == 0); %# Get the linear indices of the zero values 
colIndex = ceil(index./size(X,1)); %# Get the column index for each linear index 
X(index) = colMeans(colIndex);  %# Reassign zeroes with the column means 

而这里的测试用例:

>> X = randi([0 1],5) %# Generate a random matrix of zeroes and ones 

X = 

    0  1  0  1  0 
    1  0  0  1  1 
    0  1  0  1  0 
    1  1  1  0  1 
    0  1  0  0  1 

>> colMeans = mean(X); 
>> index = find(X == 0); 
>> colIndex = ceil(index./size(X,1)); 
>> X(index) = colMeans(colIndex) 

X = 

    0.4000 1.0000 0.2000 1.0000 0.6000 
    1.0000 0.8000 0.2000 1.0000 1.0000 
    0.4000 1.0000 0.2000 1.0000 0.6000 
    1.0000 1.0000 1.0000 0.6000 1.0000 
    0.4000 1.0000 0.2000 0.6000 1.0000 
+0

在技术上是一个很好的解决方案,但在什么情况下,您的实际平均值计算会保持?谢谢 – eat 2011-03-10 20:43:18

+0

@eat:在问题的背景下。 ;)换句话说,我不知道*为什么*或*为了什么目的* ptikobj想用列平均值替换零值,我只是简单地展示了它如何有效地完成。 – gnovice 2011-03-10 20:53:08