Choose Language Hide Translation Bar
Community Trekker

## JSL Use Lag or Dif Functions in List?

Hi Folks,

I have a list ( list = {1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17}; ) I want to modify so that it is monotonically increasing.  That is, I want to evaluate the list so that any current value < previous value is set to previous value, else, use current value.  In a JSL formula it looks like this:

If( Dif( :List, 1 ) < 0,

Lag( :List, 1 ),

:List

);

Is it possible to conduct Dif and Lag-like functions on items in a matrix?  Thanks.

1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted
Super User

## Re: JSL Use Lag or Dif Functions in List?

Matrices are fun! Loops can often be avoided if taking advantage of the matrix operations in jsl.

a = [1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17];

n = N Row( a );

pos = Loc( a[1 :: n - 1] > a[2 :: n] );

a[pos + 1] = a[pos];

Show( a );

5 REPLIES 5
Highlighted
Super User

## Re: JSL Use Lag or Dif Functions in List?

I don't believe that there are DIF and LAG functions for a matrix, but you really don't need them.  You can loop over your list/matrix and reference (i-1) or (i+1), where i is your looping index.

BTW I wouldn't use list as a variable, as it is a function in JSL.

Or, you can just sort your matrix:

a = [1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17];

b = sort ascending(a);

[1, 3, 5, 5, 7, 9, 10, 11, 13, 14, 15, 17]

Highlighted
Community Trekker

## Re: JSL Use Lag or Dif Functions in List?

Thanks PMroz,

I need the list to stay in the current order, just change the current value to the previous value if it is less than previous value.  What I'm looking to produce is:

a = [1, 3, 5, 7, 7, 9, 11, 13, 13, 14, 15, 17];

from

a = [1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17];

Highlighted
Super User

## Re: JSL Use Lag or Dif Functions in List?

Ah OK.  Then you want this:

a = [1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17];

for (i = 2, i <= nrows(a), i++,

if (a[i] < a[i-1],

a[i] = a[i-1];

);

);

[1, 3, 5, 7, 7, 9, 11, 13, 13, 14, 15, 17]

Highlighted
Super User

## Re: JSL Use Lag or Dif Functions in List?

Matrices are fun! Loops can often be avoided if taking advantage of the matrix operations in jsl.

a = [1, 3, 5, 7, 5, 9, 11, 13, 10, 14, 15, 17];

n = N Row( a );

pos = Loc( a[1 :: n - 1] > a[2 :: n] );

a[pos + 1] = a[pos];

Show( a );

Highlighted
Community Trekker

## Re: JSL Use Lag or Dif Functions in List?

Thanks MS and PMroz for two interesting ways to think about and play with matrices.