我想要类似的东西:
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 我想将当前列(即当前零值所在的列)的平均值分配给当前零值处的矩阵条目?
这是一个矢量化解决方案,它比使用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
您可以制作一个与 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));
这对我的口味来说有点“聪明”,但在我测试的单个案例(1000x1000 数组,其中大约 10% 是零)中似乎快了大约 25%。