extract without change my NaN value
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi, I have a data of 420x32x20 (precip over timexlatxlon)
And then, I need to apply this formula into each grid:
%F=n/N×100
%F = drought frequency (%)
%n = number of drought months
%N= total number of months
Example:
Over the 420 months, in one grid, i need to find the how many month with drought value (-1 till -4) and then divide by all month which is 420, then multiple by 100.
%Find the drought value
for i=1:32
for j=1:20
SPI3_SM(:,i,j) = nnz(CHIRPS_SPI3_SM(:,i,j)<-1 & CHIRPS_SPI3_SM(:,i,j)>-3);
end
end
%The amount of drought value divide by period/months
for i=1:32
for j=1:20
Freq(:,i,j)=SPI3_SM(:,i,j)/420;
end
end
%Multi by 100 to ge the percent
for i=1:32
for j=1:20
New_freq(:,i,j)=Freq(:,i,j)*100;
end
end
But, when I use NNZ, it also change my NaN into zero. Is there any other way for me to do?
댓글 수: 0
답변 (2개)
DGM
2021년 4월 23일
편집: DGM
2021년 4월 23일
Consider:
nanmask=isnan(myarray); % keep track of nans
outputarray=functionthatdoesthings(myarray); % do a thing
outputarray(nanmask)=NaN; % restore nans
Also, these loops are unnecessary. This thing
%The amount of drought value divide by period/months
for i=1:32
for j=1:20
Freq(:,i,j)=SPI3_SM(:,i,j)/420;
end
end
%Multi by 100 to ge the percent
for i=1:32
for j=1:20
New_freq(:,i,j)=Freq(:,i,j)*100;
end
end
is the same as just
Freq=SPI3_SM/420;
New_freq=Freq*100;
댓글 수: 2
DGM
2021년 5월 4일
The result from this:
nnz(CHIRPS_SPI3_MSIA(:,i,j)<-1 & CHIRPS_SPI3_MSIA(:,i,j)>-3);
is a scalar. You seem to be expecting it to be a vector, given the addressing on the LHS. The result is a 2D array, but you're making a 3D mask. If you want to apply the mask to the output, you'll have to figure out its significance conceptually and figure out how to deal with the excess information. Maybe you want to do
nanmask=squeeze(any(isnan(CHIRPS_SPI3_MSIA),1));
maybe you want
nanmask=squeeze(all(isnan(CHIRPS_SPI3_MSIA),1));
I don't know.
Jan
2021년 4월 23일
Let's simplify the code at first:
for i=1:32
for j=1:20
SPI3_SM(:,i,j) = nnz(CHIRPS_SPI3_SM(:,i,j)<-1 & CHIRPS_SPI3_SM(:,i,j)>-3);
end
end
Freq = SPI3_SM / 420;
New_freq = Freq * 100;
As far as I understand, the first loops are not useful also. Do you define SPI3_SM before the loop? What about:
SPI3_SM = sum(-3 < CHIRPS_SPI3_SM & CHIRPS_SPI3_SM < -1, 1);
What does this mean now: "it also change my NaN into zero"? Of course NaN is not in the range [-3, -1]. So what do you want to happen with NaNs?
Maybe:
SPI3_SM(any(isnan(CHIRPS_SPI3_SM), 1)) = NaN;
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!