Unusual NaN appearing from a loop

조회 수: 2 (최근 30일)
Nishant Karve
Nishant Karve 2018년 12월 3일
댓글: OCDER 2018년 12월 3일
Hi there.
I've been trying to run a loop to calculate the quartiles for each of the four columns in a dataset. The loop is as given below:
sized = size(data);
for i = 1:4
Minimum(i,1) = min(data(:,i));
Quart2(i,1) = median(data(:,i));
if rem(sized(1),2) == 0
Quart1(i,1) = median(data(data(:,1) < Quart2(i,1)));
Quart3(i,1) = median(data(Quart2(i,1) < data(:,i)));
else
Quart1(i,1) = median(Minimum(i,1): Quart2(i,1));
Quart3(i,1) = median((Quart2(i,1)):(max(data(:,i))));
end
Maximum(i,1) = max(data(:,i));
end
I'm generating a table of these results after the loop and I get something like this once I run the script:
DataSnip.PNG
The problem with this is that I don't know why the 'NaN' values appear here. When I run the line of code evaluating 'Quart1' independently in the command window for this very dataset, it gives me the correct value of 0. I'd be really grateful if someone could help me with this.
Thanks!

답변 (1개)

OCDER
OCDER 2018년 12월 3일
It seems that you are taking the median of an empty number
%EXAMPLE
data = [1 2 3];
Quart2 = 4;
Quart1 = median(data(Quart2 < data));
Quart1 =
NaN
Double check that there is no empty values. Otherwise, replace NaN's with 0's.
  댓글 수: 2
Nishant Karve
Nishant Karve 2018년 12월 3일
Thanks for the response and the alternative.
It doesn't seem like I have missing values in the dataset. Just ran a check.
OCDER
OCDER 2018년 12월 3일
When you do the logical index:
Quart2(i,1) < data(:,i)
It's possible that NO DATA agrees with this condition. So when you do this:
data(Quart2(i,1) < data(:,i)),
you get NO DATA, or an empty array, []. That's equivalent to doing this:
Quart1 = median([]) = NaN.
To fix, do this:
Quart1(isnan(Quart1)) = 0;

댓글을 달려면 로그인하십시오.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by