Naming Conventions

Scalar

Vector

Matrix

Any
rank

Non-
scalar

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
vector

ES

EV

EM

EA

EN

enclosed
Text vector

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 scalarvector

B3, I4 &c. to specify higher ranks.

Open full technical reference

ArithmeticMean

(Hide table-of-contents)

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:

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 cells

where the ''⍴ again ensures we get a scalar divisor.

Compatibility

CheckedWith: APL2, APLX, Dyalog, NARS2000

Test Cases

Show test cases

 Test;z
 ⎕IO←0
 ⎕FX⍕2 1⍴'r←ArithmeticMean na' 'r←(+/na)÷0⊥1,⍴na' ⍝ empty  → 0÷0 → 1
⍝ ---- Start Test cases (do not delete this!)
 5.5≡ArithmeticMean⍳12                            ⍝ vector → scalar
 2.5 8.5≡ArithmeticMean 2 6⍴⍳12                   ⍝ matrix → vector
 (3 2⍴0.5 2.5 4.5 6.5 8.5 10.5)≡ArithmeticMean 3 2 2⍴⍳12  ⍝ 3d → 2d
 (⍳12)≡ArithmeticMean 12 1⍴⍳12                    ⍝ 1 col  → ravel
 (4 3⍴1∊1↑,z)≡z←ArithmeticMean 4 3 0⍴⍳12          ⍝ 0 cols → all 1s or all 0s
 z≡ArithmeticMean+z←+/⎕TS                         ⍝ scalar → same scalar

For details see the PhraseBook/TestCasesGuidelines.

Test my code, both Examples and Test Cases.

See also: GeometricMean

Mentor: PhilLast

Tags: <Average> <Ave> <Avg> <Mean>


CategoryPhrasesAll - CategoryPhraseArithmetic - CategoryPhraseStatistics

PhraseBook/ArithmeticMean (last edited 2011-12-26 10:43:52 by KaiJaeger)