4

当我使用 ⌈⌿(⌈/c)- ⌊⌿(⌊/c) 计算空向量(v←⍳0) 中最大和最小数字之间的差异时,它给了我一个域错误。此语句适用于法线向量和矩阵。

如何处理异常,以便在向量为空时不会给我错误?它不应该返回任何东西或只返回一个零。

4

2 回答 2

2

守卫是最好的方法:

{0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}

请注意,实际上并不需要或不正确使用两种缩减,一种具有轴规范。也就是说,如果您希望它适用于任何维度的简单数组的所有元素,只需首先解开参数:

     {0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵},10 10 ⍴⍳100
99

或者对于任何结构或深度的数组,您可以使用“super ravel”:

     {0=⍴⍵:0 ⋄ (⌈/⍵)-⌊/⍵}∊(1 2 3)(7 8 9 10)
9

请注意,quadML(迁移级别)必须设置为 3 以确保 epsilon 是“超级 ravel”。

对矩阵进行运算时,还要注意以下等价:

     ⌈⌿⌈/10 10 ⍴⍳100
99
     ⌈/⌈/10 10 ⍴⍳100
99
     ⌈/⌈⌿10 10 ⍴⍳100
99
     ⌈⌿⌈⌿10 10 ⍴⍳100
99   

在这种情况下,不需要使用带轴的归约,并且会掩盖意图并且还可能更昂贵。最好只是解开整个事情。

于 2013-05-29T20:28:25.643 回答
1

正如我在评论中提到的,Dyalog APL 有 guards,可用于条件执行,因此您可以简单地检查空向量并给出不同的答案。

然而,这可以用更传统/纯粹的 APL 方法来实现。

此版本仅适用于一维

在 APL 字体中:

Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈⌿(⌈V)) - (⌊⌿(⌊V))
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
Z←↑(⍬≡V)↓(((⌈⌿(⌈V)) - (⌊⌿(⌊V))) 0)

或者用大括号表示,对于没有字体的人。

Z{leftarrow}DIFFERENCE V
{lamp} Calculate difference between vectors, with empty set protection
{lamp} Difference is calculated by a reduced ceiling subtracted from the reduced floor
{lamp} eg. ({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))
{lamp} Protection is implemented by comparison against the empty set {zilde}{equalunderbar}V
{lamp} Which yields 0 or 1, and using that result to select an answer from a tuple
{lamp} If empty, then it drops the first element, yielding just a zero, otherwise both are retained
{lamp} eg. <condition>{downarrow}(a b) => 0 = (a b), 1 = (b)
{lamp} The final operation is first {uparrow}, to remove the first element from the tuple.
Z{leftarrow}{uparrow}({zilde}{equalunderbar}V){downarrow}((({upstile}{slashbar}({upstile}V)) - ({downstile}{slashbar}({downstile}V))) 0)

以及为了保存的图像...

APL 差分函数

更新。多维

Z←DIFFERENCE V
⍝ Calculate difference between vectors, with empty set protection
⍝ Initially enlist the vector to get reduce to single dimension
⍝ eg. ∊V
⍝ Difference is calculated by a reduced ceiling subtracted from the reduced floor
⍝ eg. (⌈/V) - (⌊/V)
⍝ Protection is implemented by comparison against the empty set ⍬≡V
⍝ Which yields 0 or 1, and using that result to select an answer from a tuple
⍝ If empty, then it drops the first element, yielding just a zero, otherwise both are retained
⍝ eg. <condition>↓(a b) => 0 = (a b), 1 = (b)
⍝ The final operation is first ↑, to remove the first element from the tuple.
V←∊V
Z←↑(⍬≡V)↓(((⌈/V) - (⌊/V)) 0)

APL 差异多维

于 2013-05-29T18:04:53.913 回答