Here collects the C# implementation of Array utility functions for group research.
Array Multiply
Parameters: 2-d array * 2-d array
Return: 2-d array
*Multiply 2-d arrays
*Param
*/
public static double[,] ArrayMul(double[,] a, double[,] b){
if(a.GetLength(1)!=b.GetLength(0)){
WriteLine("Row number in a is NOT equal to column number in b!");
return null;
}
double[,] result = new double[a.GetLength(0),b.GetLength(1)];
for(int i=0;i<a.GetLength(0);i++) {
for(int j=0;j<b.GetLength(1);j++){
double c = 0;
for(int k=0;k<a.GetLength(1);k++){
c+=a[i,k]*b[k,j];
}
result[i,j]=c;
}
}
return result;
}
Attention:
1. To use GetLength() for the length of different dimension.
2. To use [,] for 2-d array definition.
Array Initialization
Parameters: 2-d array
Return: void
/***
*Initialize 2-d array with random doubles (with given max)
*/
public static void ArrayInit(ref double[,] a, double max){
Random rd = new Random();
for(int i=0; i<a.GetLength(0); i++){
for(int j=0; j<a.GetLength(1); j++){
a[i,j] = rd.Next((int)max)+rd.NextDouble();
}
}
}
Attention:
1. Random is defined under the namespace System, so please add `using System;'.
2. NextDouble() returns a double value (0,1), so if you need the integer part of a random value, refer to Next().
Array Presentation
Parameters: 2-d array
Return: void
/***
*Print out the entries in the given 2-d array.
*/
public static void ArrayPres(double[,] a){
for(int i=0;i<a.GetLength(0);i++){
for(int j = 0; j<a.GetLength(1); j++){
Write($"{a[i,j]} ");
}
WriteLine();
}
}