Matrix of Random Number using polar rejection - c#

I am trying to create a matrix of Random numbers using Polar Rejection method with the code below. I don't see any error but the console does not show any results. My code is below:
class Program
{
static void Main(string[] args)
{
Program.GenerateRandom();
}
public static void GenerateRandom()
{
Console.WriteLine("Please enter newtrials.");
int newTrials=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter Steps.");
int newSteps = Convert.ToInt32(Console.ReadLine());
int i = 0;
int j = 0;
double[,] v = new double[newTrials,newSteps];
double[,] d = new double[newTrials, newSteps];
double[,] l = new double[newTrials, newSteps];
double[,] Z = new double[newTrials, newSteps];
for (i = 0; i < newTrials; ++j)
{
for (j = 0; j < newSteps; ++i)
{
do
{
Random rnd = new Random();
v[i, j] = 2 * rnd.NextDouble() - 1;
d[i, j] = 2 * rnd.NextDouble() - 1; ;
l[i, j] = Math.Pow(v[i, j], 2) + Math.Pow(d[i, j], 2);
}
while (l[i, j] >= 1.0);
}
Z[i, j] = Math.Sqrt(-2 * Math.Log(l[i, j]) / l[i, j]) * v[i, j];
}
Console.WriteLine("values are:{0},{1}",Z[0,0],Z[0,1]);
Console.ReadLine();
}
}
}

I see two things that are I believe are errors in this code:
for (i = 0; i < newTrials; ++j) and for (j = 0; j < newSteps; ++i). You're incrementing the counter for the j loop in i and the counter for i loop in j. This is causing a "System.IndexOutOfRangeException" when I run your code because the j loop isn't getting incremented in the j loop and thus the loop isn't stopping.
Z[i, j] = Math.Sqrt(-2 * Math.Log(l[i, j]) / l[i, j]) * v[i, j]; at this point in the program's execution the loops have reached the bounds of the arrays you declared above. So if the user input 10 and 10 this code is calling Z[10, 10]. Since arrays are zero based Z only has upper bounds of Z[9,9] this is throwing a "System.IndexOutOfRangeException" as well.
The other consequence of the 2nd issue is that you're only writing an answer to the last index of the second dimension of the Z array. Meaning, if we use our 10 and 10 example again, results will only be written to Z[0, 9], Z[1, 9], Z[2, 9], Z[3, 9], Z[4, 9], Z[5, 9], Z[6, 9], Z[7, 9], Z[8, 9], and Z[9, 9]. I'm not sure what you're intending to do with this code but I think you have some logic errors.
I think you want something like the following:
Console.WriteLine("Please enter newtrials.");
int newTrials = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter Steps.");
int newSteps = Convert.ToInt32(Console.ReadLine());
int i = 0;
int j = 0;
double[,] v = new double[newTrials, newSteps];
double[,] d = new double[newTrials, newSteps];
double[,] l = new double[newTrials, newSteps];
double[,] Z = new double[newTrials, newSteps];
Random rnd = new Random();
for (i = 0; i < newTrials; i++)
{
for (j = 0; j < newSteps; j++)
{
do
{
v[i, j] = 2.0 * rnd.NextDouble() - 1.0;
d[i, j] = 2.0 * rnd.NextDouble() - 1.0;
l[i, j] = Math.Pow(v[i, j], 2.0) + Math.Pow(d[i, j], 2.0);
}
while (l[i, j] >= 1.0);
Z[i, j] = Math.Sqrt(-2 * Math.Log(l[i, j]) / l[i, j]) * v[i, j];
}
}
for (i = 0; i < newTrials; i++)
{
Console.Write("[");
for (j = 0; j < newSteps; j++)
{
Console.Write("{0}, ", Z[i, j]);
}
Console.Write("]\n");
}
Console.ReadLine();

Related

Im trying to fill a 2d 20x20 array with the multiplication table of 1 through 20

So far I have,
int[,] array2d = new int[20, 20];
for (int i = 1; i < array2d.GetLength(0); i++)
{
for (int j = 1; j < array2d.GetLength(1); j++)
{
array2d[i, j] = i * j ;
Console.WriteLine(array2d[i, j]);
}
}
but this is skipping some quite a few numbers, I tried to fix it by checking if I is <= but that throws a IndexOutOfRangeException
Is there some point where I made a major error? or is it a simple one.
Arrays are zero-based by default; so your array is [0..19, 0..19]; however, you want a different range: [1..20, 1..20]. We should not mix them: either (better choice)
int[,] array2d = new int[20, 20];
// i, j - array indexes
for (int i = 0; i < array2d.GetLength(0); i++)
{
for (int j = 0; j < array2d.GetLength(1); j++)
{
// since i, j are array indexes we multiply (i + 1) * (j + 1)
array2d[i, j] = (i + 1) * (j + 1);
Console.Write($"{array2d[i, j],3} ");
}
Console.WriteLine();
}
Or
int[,] array2d = new int[20, 20];
// i, j are values to be multiplied
for (int i = 1; i <= array2d.GetLength(0); i++)
{
for (int j = 1; j <= array2d.GetLength(1); j++)
{
// since i, j are values we have to compute array's indexes: i - 1, j - 1
array2d[i - 1, j - 1] = i * j;
Console.Write($"{array2d[i - 1, j - 1],3} ");
}
Console.WriteLine();
}
int[,] array2d = new int[20, 20];
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
array2d[i, j] = (i+1) * (j+1) ;
Console.WriteLine(array2d[i, j]);
}
}
Your problem was that when you define array like new int[20] then it can be iterated from 0 to 19, when you try to acces its value at index 20 you get this exception because index 20 doesnt exist in this array.
When you call arrays .GetLength method it returns its count of fields which is 20, not its maximum index which is 19.

Computing Array Determinant for NxN Recursive C#

Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion.
The logic is working right but I'm not able to get the final value computed correctly.
Here is my code for Matrix Determinant:
public static double determinant(double[,]array){
double det=0;
double total = 0;
double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];
if(array.GetLength(0)==2)
{
det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
}
else {
for (int i = 0; i <1; i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);
}
}
}
return det;
}
and about fillNewArr method it's just a method to trim the array, method is as follow:
p
ublic static double[,] fillNewArr(double[,] originalArr, int row, int col)
{
double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];
for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
{
if (i == row)
continue;
for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
{
if ( j == col) continue;
tempArray[newRow, newCol] = originalArr[i, j];
newCol++;
}
newRow++;
}
return tempArray;
}
The method is working as it supposed to "I assume" but the final result is not computed in the right way, why would that be?!
4x4 Array Example:
{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}
Final result should be -168, while mine is 104!
This bit
if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);
uses a variable total that is never used again. It should probably be something like
double subdet = determinant(fillNewArr(array, i, j));
if (j % 2 != 0) subdet *= -1;
det += array[i, j] * subdet;

Getting numbers from a matrix

Hi my problem is I can't get the numbers with more than 2 digits from this matrix if anyone can help I would appriciate it here i my code :
Console.Write("x: ");
int x = int.Parse(Console.ReadLine());
Console.Write("y: ");
int y = int.Parse(Console.ReadLine());
int[,] arr = new int[x, y];
int[,] arr2 = new int[x, y];
Random rand = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
int randNUm = rand.Next(0, 20);
arr[i, j] = randNUm;
Console.Write(arr[i, j] + " ");
if (arr[i, j] >= 10)
{
arr2[i,j] = arr[i,j]
}
}
}
Actually you have done your job, all it remains is to display the results. If
the task specifies that the printing must be done in 2 steps as you imply,
try:
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
int randNUm = rand.Next(0, 20);
arr[i, j] = randNUm;
Console.Write(arr[i, j] + " ");
if (arr[i, j] >= 10)
{
arr2[i,j] = arr[i,j]
}
}
}
Console.WriteLine("---Proceeding to 2 digit numbers---");
for (int i = 0; i < arr2.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
Console.Write(arr2[i, j] + " ");
}
}
EDIT : Consider what Henk comments and try to optimise your solution.

Matrix array in c#

I have a program that should read in an integer value x from the console, and then print out a multi dimensional. The value of the row i on column j should be i *j. For example: if I input 3, the matrix should look like this:
1 2 3
2 4 6
3 6 9
Now, I have written this code in my Main function:
Console.WriteLine("Input a value: ");
int x = int.Parse(Console.ReadLine());
int[,] arr = new int[x,x];
for (int i = 0; i < x; i--)
{
for (int j = 0; j < x; j++)
{
arr[i, j] = arr[i, j] + arr[i, j];
Console.Write(arr[i, j] + " ");
}
}
Console.ReadLine();
So, when I input 3 from my code, I get the output:
0 0 0
What am I doing wrong here?
You have to change i-- to i++.
Put Console.WriteLine() after inner for loop. It will print a line break after every x numbers to make it loop like matrix.
You're saying The value of the row i on column j should be i *j, but I can't see any i * j in your code. Change your calculations to that: arr[i, j] = i * j;.
That should be it, but because your loops run from 0 to x - 1 and you want result to be as if it was from 1 to x you have to adapt your calculations and make it arr[i, j] = (i + 1) * (j + 1);.
Complete code should be:
Console.WriteLine("Input a value: ");
int x = int.Parse(Console.ReadLine());
int[,] arr = new int[x, x];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < x; j++)
{
arr[i, j] = (i + 1) * (j + 1);
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
You´re saing that the value of arr[i, j] must be equals to i * j, but you´re not doing it on your code.
change
arr[i, j] = arr[i, j] + arr[i, j];
to
arr[i, j] = (i+1) * (j+1);
another thing that you need to change is that i are being decremented on the for loop, because of this code: i--. change it to i++
Seeing how the int[,] is full of zero's all your doing is adding zero + zero.
Seems like what you really want is this:
int[,] arr = new int[x,x];
for (int i = 0; i < x; i++)
{
for (int j = 0; j < x; j++)
{
arr[i, j] = (i+1) * (j + 1);
Console.Write(arr[i, j] + " ");
}
Console.Write("\r\n");
}
Console.ReadLine();

How can I multiply two matrices in C#?

Like described in the title, is there some library in the Microsoft framework which allows to multiply two matrices or do I have to write my own method to do this? // I've got an answer to this by now
Second question:
I wrote this multi class with a MultiplyMatrix method but it doesn't work like I want to. Can anyone help and tell where I made a mistake?
class multi
{
public void MultiplyMatrix(double[,] _A, double[,] _B, int _n, int _m, int _r)
{
int n, m, r;
double si;
n = _n;
m = _m;
r = _r;
double[,] A = new double[n, m];
double[,] B = new double[m, r];
double[,] C = new double[n, r];
A = _A;
B = _B;
try
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < r; j++)
{
si = 0;
for (int k = 0; k < m; k++)
{
si += A[i, m + k] + B[k, r + j];
}
C[i, r + j] = si;
}
}
for (int i = 0; i < C.Length; i++)
{
for (int j = 0; j < C.Length; j++)
{
Console.Write(C[i, j]+" ");
if (j % 3 == 0)
Console.WriteLine();
}
}
}
catch (IndexOutOfRangeException) { } // I always get this exception
}
}
I forgot to tell: I want to make a webservice to multiply on it.
Thanks:)
Multiplication of 2 matrixes:
public double[,] MultiplyMatrix(double[,] A, double[,] B)
{
int rA = A.GetLength(0);
int cA = A.GetLength(1);
int rB = B.GetLength(0);
int cB = B.GetLength(1);
if (cA != rB)
{
Console.WriteLine("Matrixes can't be multiplied!!");
}
else
{
double temp = 0;
double[,] kHasil = new double[rA, cB];
for (int i = 0; i < rA; i++)
{
for (int j = 0; j < cB; j++)
{
temp = 0;
for (int k = 0; k < cA; k++)
{
temp += A[i, k] * B[k, j];
}
kHasil[i, j] = temp;
}
}
return kHasil;
}
}
Whilst there's no built in Maths framework to do this in .NET (could use XNA's Maths library), there is a Matrix in the System.Windows.Media namespace. The Matrix structure has a Multiply method which takes in another Matrix and outputs a Matrix.
Matrix matrix1 = new Matrix(5, 10, 15, 20, 25, 30);
Matrix matrix2 = new Matrix(2, 4, 6, 8, 10, 12);
// matrixResult is equal to (70,100,150,220,240,352)
Matrix matrixResult = Matrix.Multiply(matrix1, matrix2);
// matrixResult2 is also
// equal to (70,100,150,220,240,352)
Matrix matrixResult2 = matrix1 * matrix2;
This is mainly used for 2D transformation:
Represents a 3x3 affine transformation
matrix used for transformations in 2-D
space.
but if it suits your needs, then there's no need for any third party libraries.
Although you can multiply matrices by an iterative approach (for loops), performing the calculations with linear algebra will clean up your code and will give you performance gains that are several times faster!
There is a free library available in nuget - MathNet.Numerics. It makes it extremely easy to multiply matrices:
Matrix<double> a = DenseMatrix.OfArray(new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
Matrix<double> b = DenseMatrix.OfArray(new double[,] { { 1 }, { 2 }, { 3 } });
Matrix<double> result = a * b;
It has no dependencies and can be used in .net core 2.0, making it an excellent choice to avoid iterative matrix multiplication techniques and take advantage of linear algebra.
There is nothing built into .NET. You will have to write the multiplication yourself or use some third party library. I've blogged about one way to achieve this comparing two different implementations : a standard naive algorithm and one using unsafe code.
CSML - C# Matrix Library - is a compact and lightweight package for numerical linear algebra. Many matrix operations known from Matlab, Scilab and Co. are implemented.
See this!
There are no such built in libraries. Unless you are using XNA - it has a Matrix class, though it is limited and designed for 3D games.
There are many matrix libraries for .NET though.
namespace matrix_multiplication
{
class Program
{
static void Main(string[] args)
{
int i, j;
int[,] a = new int[2, 2];
Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
a[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("First matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(a[i,j]+"\t");
}
Console.WriteLine();
}
int[,] b = new int[2, 2];
Console.WriteLine("Enter no for 2*2 matrix");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
b[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("second matrix is:");
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Matrix multiplication is:");
int[,] c = new int[2, 2];
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
c[i,j]=0;
for (int k = 0; k < 2; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
Console.Write(c[i, j]+"\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
output
Enter no for 2*2 matrix
8
7
6
0
First matrix is:
8 7
6 0
Enter no for 2*2 matrix
4
3
2
1
second matrix is:
4 3
2 1
Matrix multiplication is:
46 31
24 18
Below is the method to multiply int[3,4] matrix with int[4,3] matrix, it has time complexity of O(n cube) or Cubic time
class Program
{
static void Main(string[] args)
{
MultiplyMatrix();
}
static void MultiplyMatrix()
{
int[,] metrix1 = new int[3,4] { { 1, 2,3,2 }, { 3, 4,5,6 }, { 5, 6,8,4 } };
int[,] metrix2 = new int[4, 3] { { 2, 5, 3 }, { 4, 5, 1 }, { 8, 7, 9 }, { 3, 7, 2 } };
int[,] metrixMultplied = new int[3, 3];
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
for(int i=0;i<4;i++)
{
metrixMultplied[row, col] = metrixMultplied[row, col] + metrix1[row, i] * metrix2[i, col];
}
Console.Write(metrixMultplied[row, col] + ", ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
Here is my code : 4*4 matrix
for (int i = 0; i < 4; i++)
{
int column = 0;
while (column < 4)
{
int count = 0;
for (int j = 0; j < 4; j++)
{
matrixResult[i, column] += Convert.ToInt32(matrixR[i, j] * matrixT[count, column]);
count = count + 1;
}
column = column + 1;
}
}
If you have a helper to generate, iterate and populate an int[,] matrix like this one:
public class VisitMatrix{
public static int[,] execute(int rows, int columns, Func<int, int, int> fn)
{
int[,] result = new int[rows, columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
result[i, j] = fn(i, j);
}
}
return result;
}
}
Now matrix multiplication is as trivial as doing (supposing m1.GetLength(1) == m2.GetLength(0)):
public class MultiplyMatrices{
public static int[,] execute(int[,] m1, int[,] m2, int modulus = 10)
{
return VisitMatrix.execute(m1.GetLength(0), m2.GetLength(1), (i, j) =>
Enumerable.Range(0, m1.GetLength(1)-1)
.Select(k => m1[i, k] * m2[k, j])
.Aggregate(0, (a, b) => a + b, e => e % modulus)
}
}

Categories

Resources