Hi, I have a dataset e.g like this 44 44 0; 3 3 0; 132 133 0; 45 46 42; and want to replace the zeros with the average of each row (each row represents one variable). I know how to do it for each row individually, was wondering if there is a faster way though for when dealing with a large matrix?? Thanks !

 采纳的回答

Guillaume
Guillaume 2017-7-17
编辑:Guillaume 2017-7-17
If the 0s are supposed to indicate missing values, then you should be using NaN instead. Assuming that the mean is supposed to be taken without the 0s:
m = [44 44 0; 3 3 0; 132 133 0; 45 46 42;]
m(m == 0) = NaN; %replace 0 with NaN
mu = repmat(mean(m, 2, 'omitnan'), 1, size(m, 2)); %calculate mean and replicate to same size as M
m(isnan(m)) = mu(isnan(m)) %replace NaNs by mean

更多回答(1 个)

Hi,
It seems you are trying to replace all the 0's in a matrix with the mean of the corresponding row. For example:
44 44 0
3 3 0
132 133 0
45 46 42
becomes
44 44 29.33
3 3 2
132 133 88.33
45 46 42
This can be done with simple matrix operations:
function[result] = replace0sWithMean(M)
% Finds the mean column vector by averaging each row
mu = mean(M, 2);
% Adds the mean column vector to the original matrix
added = M + mu;
% added(:,:) ~= mu(:) returns a boolean matrix where the 1's correspond to non-zero's in the original matrix
% Piece-wise multiply this result by the mean vector
% Subtract this quantity from the sum computed earlier in order to restore each original non-zero value
result = added - (added(:,:) ~= mu(:)) .* mu
end
As Guillaume wonderfully pointed out the case in which we don't want the 0's to be involved in the calculation of the means, use the following code snippet instead:
function[result] = replace0sWithMean(M)
temp = M;
temp(temp==0) = NaN;
mu = mean(temp, 2, 'omitnan');
added = M + mu;
result = added - (added(:,:) ~= mu(:)) .* mu;
end

1 个评论

I would suspect that the mean is to be taken without the 0s.

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Interpolation of 2-D Selections in 3-D Grids 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by