How to find out standard deviation of a matrix when there is a lot of NaN values?
25 views (last 30 days)
Show older comments
Ashfaq Ahmed
on 14 Dec 2021
Commented: Ashfaq Ahmed
on 14 Dec 2021
Hi altruists,
I have a 71*294 matrix that contains a lot of NaN values.
In fact, the first 7 rows, the last 7 rows, and row 30 to 41 are just NaNs! But the rest of the matrix has values. I want to calculate the row-wise std (standard deviation). How can I write down the code that automatically neglects the NaNs and calculate the std of the non NaN values?
0 Comments
Accepted Answer
Kevin Holly
on 14 Dec 2021
Edited: Kevin Holly
on 14 Dec 2021
A = rand(9,9);
A(3,4) = NaN;
A(7,8) = NaN;
A(8:9,:) = NaN
B = std(A,0,2,'omitnan')
3 Comments
Steven Lord
on 14 Dec 2021
Looking at the Syntax section of the documentation page those three inputs match the (A, w, dim) syntax. They could also match the (A, w, vecdim) syntax but since 2 is a scalar those syntaxes would do the same thing.
Both the Description section and the Input Argument section on that page go into more detail about the meaning of the A, w, and dim inputs.
Kevin Holly
on 14 Dec 2021
Edited: Kevin Holly
on 14 Dec 2021
From the documentation on the function provided:
S = std(A,w,dim) returns the standard deviation along dimension dim for any of the previous syntaxes. To maintain the default normalization while specifying the dimension of operation, set w = 0 in the second argument.
The first input to the function, A, is your matrix. The second input, w, is the weight (default is 0 which I had chosen). The third is the dimension to operate along. In this case, 2 was chosen so that the standard deviation of the elements would be calculated in each row. A value of 1 (default value) would calculate the standard deviation for each column.
More Answers (1)
Voss
on 14 Dec 2021
std(x,[],2,'omitnan')
where x is your matrix, 2 tells std to go by row, and 'omitnan' tells std to ignore NaNs in x.
See Also
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!