Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the average of each row in a matrix in APL? and the highest average?

Tags:

matrix

apl

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.

like image 522
judah Avatar asked Nov 20 '25 10:11

judah


1 Answers

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
like image 190
voidhawk Avatar answered Nov 22 '25 02:11

voidhawk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!