我希望有类似的东西:
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我想将当前列的平均值(即当前零值所在的列)分配给当前零值的矩阵条目?
答案 0 :(得分: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
答案 1 :(得分: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%(1000x1000阵列,其中约10%是零)。