필터 지우기
필터 지우기

Perplexed by logical condition result

조회 수: 3 (최근 30일)
Jared
Jared 2014년 8월 3일
답변: Star Strider 2014년 8월 3일
I have a matrix that is a mixture of numbers and NaNs by construction. I looking through answers as to how to use functions like GEOMEAN and MEAN on these type of matrices while ignoring the NaNs in these calculations. I found a response indicating I could use the following structure:
condition=isnan(A)
B=geomean(A(~condition))
The "condition" assignment statement works like a charm. In my case it creates an 87x181 logical matrix which is the same dimension as A. However, the statement "A(~condition)" creates a column vector that stacks all my numerical data from A on top of each other instead of preserving the 87x181 structure. This of course completely screws up the GEOMEAN calculation since it returns a single number instead of 181 different numbers.
Appreciate any help,
JK

채택된 답변

Star Strider
Star Strider 2014년 8월 3일
If you have geomean, you have the Statistics Toolbox. If you want to take the geometric mean of your array (with NaN values included, use nanmean of the logs of the values:
A = randi(10, 15, 20);
A(A == 5) = NaN;
B = exp(nanmean(log(A)));
A bit indirect, but it gets you the result you want, with the dimensions you want.

추가 답변 (1개)

John D'Errico
John D'Errico 2014년 8월 3일
편집: John D'Errico 2014년 8월 3일
Well, what do you expect?
A = [1 2;NaN 4];
isnan(A)
ans =
0 0
1 0
Suppose I tried A(~isnan(A)) out? Would you expect to see a resulting matrix with one element in the first column, and two elements in the second column? Surely you understand that MATLAB does not allow this. A 2-d MATRIX in MATLAB is a square or rectangular array of numbers.
As such, the only result that can be is what MATLAB does do:
A(~isnan(A))
ans =
1
2
4
There are tools of course that can handle the computations you apparently wish to do, such as nanmean.

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by