What about Matrices?
As Kartik V shows,
mean(x(~isnan(x)))
will work for vectors. However, if you have an n-by-m matrix and want to calculate the standard deviation of the random NaN, you will have to run a for loop.
Scenario example
Imagine a data matrix of the form:
A = [1 0 NaN; 0 3 4; 0 NaN 2] A = 1 0 NaN 0 3 4 0 NaN 2
Running mean(A(~isnan(A))) gives:
ans = 1.4286
This is due to the fact that logical indexing effectively "aligns" the matrix into a vector.
Looping Solution (Column Average)
Assuming you want to calculate the average of a column, the loop solution will look like this:
% Preallocate resulting mean vector nCols = size(A, 2); mu = zeros(1, nCols); % Compute means for col = 1:nCols mu(col) = mean(A(~isnan(A(:, col)), col)); end
Result:
mu = 0.3333 1.5000 3.0000
Looping Solution (cross section average)
Assuming you want to calculate the rms value, the loop solution will look like this:
% Preallocate resulting mean vector nRows = size(A, 1); mu = zeros(nRows, 1); % Compute means for row = 1:nRows mu(row) = mean(A(row, ~isnan(A(row, :)))); end
Result:
mu = 0.5000 2.3333 1.0000
source share