how to use if when there is NAN

1 Ansicht (letzte 30 Tage)
Qian cao
Qian cao am 2 Jan. 2016
Kommentiert: dpb am 2 Jan. 2016
Hi all
I have a time series price matrix as follows. At each time, I need to judge if the current price is larger than the average of the last two prices in its same column, if yes, make it 1, otherwise it is 0. When there is NaN included in the if judgement, make it NaN. e.g, w(3,1) and w(4,1) are both NaN because we can not compare if w(4,1) larger than the avarage of w(3,1)and w(2,1)because p(2,1) is NaN and the comparison is therefore invalid. I tried to use for for loop but it makes the processing kind of complicated and it seems not be working
for i=1:8
for j=1:3
w(i,j)=(a(i,j)>mean(a(i-1:i-2,j)))
end
end
I am seeking for a more efficient function. Thank you very much. BR, Jessie
p=
NaN NaN 3
NaN 2 4
2 1 5
1 1 1
2 3 2
3 0 NaN
1 2 NaN
4 NaN NaN
so the expected result is
w=
NaN NaN NaN
NaN NaN NaN
NaN NaN 1
NaN 0 0
1 1 0
1 0 1
0 1 NaN
1 1 NaN

Antworten (1)

dpb
dpb am 2 Jan. 2016
Yeah, compute the means first and then do the comparison over the valid regions. You can augment sizes later however you so choose...
>> wt=[0.5 0.5]; % filter weights for window 2 means
>> mn=filter(wt,1,p,nan) % compute means w/ valid ranges only
mn =
NaN NaN NaN
NaN NaN 3.5000
NaN 1.5000 4.5000
1.5000 1.0000 3.0000
1.5000 2.0000 1.5000
2.5000 1.5000 NaN
2.0000 1.0000 NaN
2.5000 NaN NaN
>> w=double(p(3:end,:)>mn(2:end-1,:)); % weighting comparison over valid range
>> w(isnan(p(3:end,:))|isnan(mn(2:end-1,:)))=nan % identify missing value locations
w =
NaN NaN 1
NaN 0 0
1 1 0
1 0 NaN
0 1 NaN
1 NaN NaN
>>
NB: There are only N-2 valid locations; the available data from the third to the last is compared to the first valid mean (2nd in the array) to the next-to-last since there's no observation against which to compare the last valid computed mean. This leaves a computed array of six observations from your initial eight points; as noted you can adjust this however needed to fit the remainder of the application by augmenting whichever end needs it for desired alignment.
  1 Kommentar
dpb
dpb am 2 Jan. 2016
BTW, I think your posited answer has a couple of mistakes in it...

Melden Sie sich an, um zu kommentieren.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by