3
votes

I'm trying to find the average of each row in a matrix.

I have two matrices.
One matrix, NAMES, holds a flat list of names (there are 3 names).
The other matrix,GRADES, contains numbers.
Each row in GRADES corresponds to a name in NAMES.

I'd like to write a function that would output:

Name AverageOfNumbersInRow
Name AverageOfNumbersInRow
Name AverageOfNumbersInRow

I'd also like to write a function that would output the Name that has the highest average:

Name

For example, for:

GRADES←3 4 ⍴ 98 34.5 78.9 34.7 22.3 33.9 23.8 24.11 100 89.3 92.6 87.9
NAMES←3 4 ⍴ 'JaneBob Mark'

I'd like

Mark      

I'm using NARS2000.

2
@KenWhite No, APL code tends to eschew loops, and instead deal with arrays all at once. This is a sensible question as the classic APL formula for average computes the column average.Adám
@Adám What's the classic APL formula for column average?judah
Still assuming Dyalog APL (please do state!): +⌿÷≢Adám
Your output specifications are ambiguous. For the table, do you want a nested result, a heterogeneous flat matrix, or a homogenous character matrix? For the highest averaging, in case of a tie, do you want the first, any, or all names with highest average?Adám

2 Answers

2
votes

Answering in Dyalog APL since the question was tagged with APL:

The rank operator is nice for operations like these. The block of code (+/÷≢)⍤1 will take the average (sum divided by length is (+/÷≢)) and apply it against the rows (rank number 1) in a matrix. Example:

      names←'tom' 'dick' 'harry'
      numbers←3 3⍴?⍨9
      numbers
9 5 8
6 1 2
4 3 7
      names,⍪(+/÷≢)⍤1⊢numbers
 tom    7.333333333
 dick   3          
 harry  4.666666667

EDIT due to additional information

In NARS2000, to find the name with the highest average with the data in the format stated, you can use {⍺⌷⍨(⊢⍳⌈/)(+/÷≢)⍤1⊢⍵}:

      GRADES←3 4 ⍴ 98 34.5 78.9 34.7 22.3 33.9 23.8 24.11 100 89.3 92.6 87.9
      NAMES←3 4 ⍴ 'JaneBob Mark'
      f←{⍺⌷⍨(⊢⍳⌈/)(+/÷≢)⍤1⊢⍵}
      NAMES f GRADES
Mark
0
votes

Answer in NARS2000.

"b" is a column of 6 names, "a" is one 6 rows matrix of 5 votes, "c" would be the mean each row of "a"

  b←⍪"one" "two" "treqq" "qu" "cin" "six" 
  a←6 5⍴↑,/{⍵?10}¨30⍴1
  a
10 8 3 2 6
 3 9 9 1 7
 4 4 9 1 9
 2 1 8 1 8
 5 1 7 2 6
 3 9 4 4 9
  c←(2⌷⍴a)÷⍨+/a
  c
5.8 5.8 5.4 4 4.2 5.8 
  b,c
 one   5.8 
 two   5.8 
 treqq 5.4 
 qu    4   
 cin   4.2 
 six   5.8 
  ⎕fmt  ,b[(+/c[↑⍒c]=c)↑⍒c;]
┌3───────────────────┐
│┌3───┐ ┌3───┐ ┌3───┐│
││ one│ │ two│ │ six││
│└────┘ └────┘ └────┘2
└∊───────────────────┘