[ncl-talk] get first index of each sequence

Dave Allured - NOAA Affiliate dave.allured at noaa.gov
Mon Mar 6 08:05:29 MST 2023


Chang, use the same general approach.  In this case, compare x(n-1) to
x(n), and remember the positions where the value changed.  The essential
logic is in the single line "change =".

    x = (/1,1,1,5,5,5,5,31,31/)
    nx = dimsizes (x)
    previous = new (nx, typeof (x))
    previous(0) = x(0) - 1      ; need this to get correct answer for first
position
    previous(1:nx-1) = x(0:nx-2)       ; vector shifted one position to the
right
    change = (x(:) .ne. previous(:))   ; all places that changed value
    istarts = ind (change)

    print (istarts+"")
    (0)     0
    (1)     3
    (2)     7


On Mon, Mar 6, 2023 at 2:06 AM Xi Chang <xi.chang01 at gmail.com> wrote:

> Thanks a lot Dave. Would you please suggest me hot get the first index of
> each sequence without any missing values in between. For example, i would
> like to get the first index of each sequence marked by flags:
>
> x= (/1,1,1,5,5,5,5,31,31/)
>
> Results will be: 0, 3, and 7
>
> Thank you!
> Chang,
>
>
> On Mon, Feb 6, 2023 at 17:01 Dave Allured - NOAA Affiliate <
> dave.allured at noaa.gov> wrote:
>
>> When analyzing sequences, it is often useful to compare adjacent elements
>> by using a vector shifted by one position.  Then find an expression that is
>> true in the positions of interest, and false everywhere else.
>>
>>     status = .not. ismissing (x)
>>     nx = dimsizes (x)
>>     previous = new (nx, logical)
>>     previous(0) = False      ; need this to get correct answer for first
>> position
>>     previous(1:nx-1) = status(0:nx-2)       ; vector shifted one position
>> to the right
>>     change = status(:) .and. .not. previous(:)     ; all places that
>> changed from missing to not
>>     istarts = ind (change)
>>
>>     print (istarts+"")
>>     (0)     4
>>     (1)     12
>>     (2)     16
>>
>>
>> On Mon, Feb 6, 2023 at 7:18 PM Xi Chang via ncl-talk <
>> ncl-talk at mailman.ucar.edu> wrote:
>>
>>> Hi NCL community,
>>>
>>> Is there anyone who can help me on how to return the first index of each
>>> sequence in 1D data?
>>> For example,
>>>
>>> x = (/-999,-999,-999,-999,1,1,1,1,1,-999,-999,-999,1,1,1,-999,1,1,1/)
>>> x at _FillValue=-999
>>>
>>> There are 3 sequences of data in that 1D time series, how could I get
>>> the first index of each sequence, so that the answer would be:
>>>
>>> (0) 4
>>> (1) 12
>>> (2) 16
>>>
>>> Thanks
>>> Chang
>>>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.ucar.edu/pipermail/ncl-talk/attachments/20230306/47ae5ec2/attachment.htm>


More information about the ncl-talk mailing list