How can I sort a list/matrix in a function?

337 views Asked by At

When I try to use SortA and SortD in a function:

Define test()=
Func
© Convoluted way of returning [0 1 2 4 5; 4 1 3 5 2]
Local a,b
a:=[1 5 2 0 4]
b:=[1 2 3 4 5]
SortA a,b
Return colAugment(a,b)
EndFunc

I get the error Invalid in a function or current expression. I think this is because SortA modifies variables and this isn't allowed in a function, only in a program. Is there a way to sort a list or matrix in this way in a function?

3

There are 3 answers

2
GBR On

The function SortA, SortD appears to work fine on the App calculator, and as a Program, but not with in a function.

Check this and correct a few mistakes Regards

Code Running it

1
Logan Tischler On

All you have to do is declare b as a local variable (as well as a):

Local a,b

And then it shouldn't return the error you mentioned.

I hope that helped!

0
Lauren Yim On

While this doesn’t sort matrices, I made this function that sorts a list in ascending order. I don’t think it’s very efficient though as it just loops through the list and calls min, but my use case was only for small lists up to around 5 elements and I wanted it to be quick to type on my handheld calculator.

© Can't name it sorta due to the builtin
Define srta(xs)=
Func
Local ys,x,i,j,k,l0,l
l0:=dim(xs)
ys:={}
For i,l,l0
  x:=min(xs)
  ys:=augment(ys,{x})
  l:=dim(xs)
  For j,1,l
    If xs[j]=x Then
      © This splices the element at j (x) out of the list xs
      xs:=seq(xs[k+piecewise(0,k<j,1)],k,1,l-1)
      Exit
    EndIf
  EndFor
EndFor
Return ys
EndFunc

To sort it in descending order, replace min with max.