我想有这样的:如何将列平均值分配给矩阵的该列中的特定值?
Mu = mean(X); % column-wise means
X(X == 0) = Mu(current_column); % assign the mean value of the current column
% to the zero-element
但我怎么告诉MATLAB我要分配的当前列的平均值(即当前列中的零值是)以矩阵项当前的零值?
我想有这样的:如何将列平均值分配给矩阵的该列中的特定值?
Mu = mean(X); % column-wise means
X(X == 0) = Mu(current_column); % assign the mean value of the current column
% to the zero-element
但我怎么告诉MATLAB我要分配的当前列的平均值(即当前列中的零值是)以矩阵项当前的零值?
你可以做一个阵列相同的形状,包含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%是零)。
这是一个矢量化解决方案,它比使用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
我喜欢第二个! – ptikobj 2011-03-10 18:39:14
然而,应用第二个产生:“???下标索引必须是真正的正整数或逻辑。”可能是因为手段(X)? – ptikobj 2011-03-10 18:45:37
糟糕。我的意思是“mean(X)”,而不是“means(X)”。将编辑,道歉的方式,将废话你的评论:-)。 – 2011-03-10 19:07:34