简体   繁体   中英

How to calculate average in visual studio vb.net code ? (matrix)

I need to calculate average of the elements of the matrix in vb.net

This is my matrix

5 2 1 2
5 5 2 -2
1 5 -1 1
1 -1 -5 -2

One of these may be your "matrix"

' multidimensional array
Dim m1(,) As Integer =
    {
        {5, 2, 1, 2},
        {5, 5, 2, -2},
        {1, 5, -1, 1},
        {1, -1, -5, -2}
    }
' jagged array
Dim m2()() As Integer =
    {
        New Integer() {5, 2, 1, 2},
        New Integer() {5, 5, 2, -2},
        New Integer() {1, 5, -1, 1},
        New Integer() {1, -1, -5, -2}
    }
' list of lists
Dim m3 = New List(Of List(Of Integer)) From
    {
        New List(Of Integer)() From {5, 2, 1, 2},
        New List(Of Integer)() From {5, 5, 2, -2},
        New List(Of Integer)() From {1, 5, -1, 1},
        New List(Of Integer)() From {1, -1, -5, -2}
    }

And for each of those matrices, here is how you can calculate the average

Dim a1 As Double
For i = m1.GetLowerBound(0) To m1.GetUpperBound(0)
    For j = m1.GetLowerBound(1) To m1.GetUpperBound(1)
        a1 += m1(i, j)
    Next
Next
a1 /= (m1.GetUpperBound(0) - m1.GetLowerBound(0) + 1) * (m1.GetUpperBound(1) - m1.GetLowerBound(1) + 1)

Dim a2 As Double
' count items because jagged array can have different # of items in each level
Dim c2 As Integer 
For i = m2.GetLowerBound(0) To m2.GetUpperBound(0)
    For j = m2(i).GetLowerBound(0) To m2(i).GetUpperBound(0)
        a2 += m2(i)(j)
        c2 += 1
    Next
Next
a2 /= c2

Dim a3 = m3.SelectMany(Function(l) l).Average()

Console.WriteLine($"Multidimensional avg: {a1}")
Console.WriteLine($"Jagged avg: {a2}")
Console.WriteLine($"List of List avg: {a3}")

Multidimensional avg: 1.1875
Jagged avg: 1.1875
List of List avg: 1.1875

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM