문제

I'm new to APL. How can I remove unwanted elements from an array?

For example:

 X←1 2 3 4 5 6 7 8 9

Now I want to remove elements of X that equal either 4 or 6. I tried

X←4↓X

to drop 4 from X, but it didn't work. Thanks in advance.

도움이 되었습니까?

해결책

Try this, assuming x = 1 2 3 4 5 6 7 8 9

x←(~x∊4 6)/x

Explaination

Find 4 and 6 in the array x with x∊4 6 which outputs: 0 0 0 1 0 1 0 0 0 (the locations of 4 and 6)

Now, Negate this array with ~ which outputs 1 1 1 0 1 0 1 1 1 (the opposite of the above)

Apply this to the array x with /x which leaves you with 1 2 3 5 7 8 9

Finally, assign this to x with x← leaving x with your desired output.

다른 팁

The appropriate way to do this is using the without function (dyadic tilda):

      x←1 2 3 4 5 6 7 8 9
      x~4 6
1 2 3 5 7 8 9

However, if you need the location of the items you want removed for additional purposes (perhaps to remove the corresponding items from some some other related array) then the technique by MrZander above is appropriate.

You could create a binary mask such that 0 implies "element is 4 or 6" and 1 implies "element is neither 4 nor 6". Then you select from the array using this mask.

(~(6=X)∨(4=X))/X

For most purposes, the without function mentioned by Paul Mansour is a better approach. but if you wanted to use a bit-mask, try:

(~(X¹4 6))/X

(Note that "¹" is the "member" primitive, normally represented as an epsilon character.)

This selects all elements of X that are either 4 or 6, then applies a not to create a boolean that is 0 for all elements that are 4 or 6, and uses that to compress X, removing all 4s and 6s. Perhaps more useful would be:

((bv{gets}~X{member}4 6))/X

This would save the compression vector (aka mask) in a separate variable bv. If there are several structures that should be kept in sync, bv could then be used to compress the others to match X. Of course, a more complex condition for bv would be likely in real working code. ({gets} stands for the assignment operation, normally represented by a leftward arrow.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top