Naming Conventions |
|||||
|
Scalar |
Vector |
Matrix |
Any |
Non- |
Boolean |
BS |
BV |
BM |
BA |
BN |
Integer |
IS |
IV |
IM |
IA |
IN |
Float |
FS |
FV |
FM |
FA |
FN |
Numeric |
NS |
NV |
NM |
NA |
NN |
Character |
CS |
CV |
CM |
CA |
CN |
Enclosed |
ES |
EV |
EM |
EA |
EN |
enclosed |
TS |
TV |
TM |
TA |
TN |
Simple |
SS |
SV |
SM |
SA |
SN |
Any |
AS |
AV |
AM |
AA |
AN |
phrase e.g.: .X...Y. ⍝ X←BS; Y←IV |
|||||
combinations: use ISV for Integer scalar∨vector |
|||||
B3, I4 &c. to specify higher ranks. |
|||||
ArithmeticMean
This phrase should work in all APLs to produce the arithmetic mean or average of each row of any simple numeric array. It is a summary function in the sense that it is rank reducing: (⍴result) ←→ (¯1↓⍴argument)
(+/N)÷0⊥1,⍴N ⍝ N←NA
Examples
⎕FX⍕2 1⍴'r←ArithmeticMean na' 'r←(+/na)÷0⊥1,⍴na'
⍳12
0 1 2 3 4 5 6 7 8 9 10 11
ArithmeticMean⍳12
5.5
ArithmeticMean 2 6⍴⍳12
2.5 8.5
ArithmeticMean 3 2 2⍴⍳12
0.5 2.5
4.5 6.5
8.5 10.5
ArithmeticMean 12 1⍴⍳12
0 1 2 3 4 5 6 7 8 9 10 11
How not to do it!
The oft quoted way to code this; and as Roger Hui has pointed out, the example that too many use to show the conciseness and power of APL; is:
(+/nv)÷⍴nv
which works more or less for a numeric vector but is:
- empty for a scalar;
- a one-element vector rather than a scalar for a vector;
correct for 2×2 matrices;
correct for 2×n matrices whose sum (+/) is all zeros;
wrong for any other 2×n matrix;
- LENGTH ERROR for any other 2D matrix; and
- RANK ERROR for higher rank arrays.
The 0⊥1, before the shape in the phrase at the top ensures that we always have a valid scalar divisor which is one for a scalar. Using the perhaps more obvious ¯1↑ gives DOMAIN ERROR for a scalar and incorrect rank for vectors.
Conforming Variants
It can be made to return zeros instead of ones for empty rows - no columns:
(+/na)÷1⌈0⊥⍴na ⍝ gives 0 for empty rows
It can be made to return the average of all the major cells rather than that of each of the rows; through the first rather than last dimension:
(+⌿na)÷''⍴(⍴na),1 ⍝ gives 1 for no major cells
(+⌿na)÷1⌈''⍴(⍴na),1 ⍝ gives 0 for no major cellswhere the ''⍴ again ensures we get a scalar divisor.
The ,1 is still necessary in the last phrase above because ''⍴⍳0 is a DOMAIN ERROR in APL2.
Apart from APL2 where it isn't implemented, ⍬⍴ can be used rather than ''⍴ to get the first element of the shape vector.
In Dyalog (with ⎕ML=3) ↑⌽ is quicker than 0⊥ for the last element of the shape vector because it is a special case idiom.
Compatibility
CheckedWith: APL2, APLX, Dyalog, NARS2000
Test Cases
Show test cases
Test my code, both Examples and Test Cases.
See also: GeometricMean
Mentor: PhilLast
Tags: <Average> <Ave> <Avg> <Mean>
CategoryPhrasesAll - CategoryPhraseArithmetic - CategoryPhraseStatistics
APL Wiki