How to make a matrix multiplication in a task - c#

I am unable unable to get the product of matrices in a task in order to run it
in several instances. I think the task is not properly doing the multiplication and calling several 0's.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _010029428_Multiplicacion
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n;
Random rnd = new Random((int)DateTime.Now.Ticks & 0x000fff);
Console.WriteLine("Ingrese el numero de renglones y columnas: ");
m = Convert.ToInt32(Console.ReadLine());
n = Convert.ToInt32(Console.ReadLine());
int[,] a = new int[m, n];
Console.WriteLine("first Matrix");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
a[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("First matrix is: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
int[,] b = new int[m, n];
Console.WriteLine("Second Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
b[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("The second matrix is:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("The result is :");
int[,] c = new int[m, n];
var multiplicacion = new Task(() =>
{
for (j = 0; j < n; j++)
{
c[i, j] = 0;
for (int k = 0; k < n; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
});
for (i = 0; i < m; i++)
{
multiplicacion.Start();
}
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
}
}
}
The code is using multiplicacion.start() to run it asynchronously
Not sure what the problem may be

There are several problems.
First: You cannot create just one task and run it multiple times at once. New Task() must be created for each value of "i".
Second: You cannot use global variable ("j") and mutate it in a task that runs asynchronously, without proper synchronization. This would result in program crash or wrong result. Each task must have it's own (local) variable ("jj") if it needs to change it. Read-only variables (i, a, b, c, m, n) are usually safe to use, but it is better to pass them as arguments.
Third: You must wait for all tasks to finish before you write result to screen.
Four: Running task asynchronously has significant performance overhead. So unless you matrices are really huge (probably at least hundreads of rows and columns), calculating result in several asynchronous tasks is probably much slower than simple synchronous calculation on main thread.
Example of how to make it work follows. Code is still ugly and not wery good, but should work and give you some starting point for further improvements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _010029428_Multiplicacion
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n;
Random rnd = new Random((int)DateTime.Now.Ticks & 0x000fff);
Console.WriteLine("Ingrese el numero de renglones y columnas: ");
m = Convert.ToInt32(Console.ReadLine());
n = Convert.ToInt32(Console.ReadLine());
int[,] a = new int[m, n];
Console.WriteLine("first Matrix");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
a[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("First matrix is: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
int[,] b = new int[m, n];
Console.WriteLine("Second Matrix: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
b[i, j] = rnd.Next(1, 4);
}
}
Console.WriteLine("The second matrix is:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(b[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("The result is :");
int[,] c = new int[m, n];
Task[] tasks = new Task[m];
for (i = 0; i < m; i++)
{
var multiplicacion = new Task((parameter) =>
{
int ii = (int)parameter;
for (int jj = 0; jj < n; jj++)
{
c[ii, jj] = 0;
for (int k = 0; k < n; k++)
{
c[ii, jj] += a[ii, k] * b[k, jj];
}
}
},
i);
tasks[i] = multiplicacion;
multiplicacion.Start();
}
Task.WaitAll(tasks);
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(c[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}

Related

How to save a pyramid into array of chars?

I need help with checking IF the position in array must save ' ' or '*' for later in program to print out a pyramid.
static void Main(string[] args)
{
Console.WriteLine("Enter size: ");
int s = int.Parse(Console.ReadLine());
char[,] pyramid = new char[s, s * 2 - 1];
FillArray(pyramid);
Out(pyramid);
Console.ReadLine();
}
static void FillArray(char[,] t)
{
for (int i = 0; i < t.GetLength(0); i++)
{
for (int j = 0; j < t.GetLength(1); j++)
{
if (j == t.GetLength(1) / 2 || j == t.GetLength(1) / 2 + i || j == t.GetLength(1) / 2 - i)
{
t[i, j] = '*';
}
else t[i, j] = ' ';
}
}
}
static void Out(char[,] t)
{
for (int i = 0; i < t.GetLength(0); i++)
{
for (int j = 0; j < t.GetLength(1); j++)
{
Console.Write(t[i, j]);
}
Console.WriteLine();
}
}
At the moment I get out something like this:
The code should be like this
int i, j, n;
Console.WriteLine("Enter size: ");
n = int.Parse(Console.ReadLine());
for (i = 0; i < n; i++)
{
for (j = 1; j <= n - i; j++)
Console.Write(" ");
for (j = 1; j <= 2 * i - 1; j++)
Console.Write("*");
Console.Write("\n");
}

I want to sort matrix in ascending order in C# without any function

Matrix entered the result is:
1 5 48
7 11 3
P.S User can enter any number not like above.
It should be in ascending order: 1 3 5 7 11 48
I used loop but it does not work properly
using System;
namespace MainClass
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n, sum = 0;
int count = 0;
Console.Write("The MxN matrix\n");
Console.Write("Enter the number of rows and columns of the matrix :\n");
Console.Write("Rows (M): ");
m = Convert.ToInt32(Console.ReadLine());
Console.Write("Columns (N): ");
n = Convert.ToInt32(Console.ReadLine());
int[,] arr = new int[m, n];
Console.Write("Enter elements in the first matrix :\n");
/* Entering matrix elements */
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
Console.Write("element - [{0}],[{1}] : ", i, j);
arr[i, j] = Convert.ToInt32(Console.ReadLine());
/* Calculating odd numbers of the matrix */
if (arr[i, j] % 2 != 0)
{
sum += arr[i, j];
}
}
}
Console.Write("\nThe matrix is:\n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
Console.Write("{0} ", arr[i, j]);
Console.Write("\n");
}
Console.Write("\nThe sum of odd numbers is: {0}", sum);
/* Sorting Matrix in ascending order*/
for (i = 0; i < m; i++)
{
for (j = i+1; j < n; j++)
{
for (int j1 = 0; j1 < n; j1++ )
{
if (arr[i, j] > arr[i, j1]){
int temp = arr[i, j];
arr[i, j] = arr[i, j1];
arr[i, j1] = temp;
}
}
}
}
Console.Write("\nAscending order: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
Console.Write("{0} ", arr[i, j]);
}
Console.Read();
}
}
}
Here you are.
using System;
namespace MainClass
{
class Program
{
static void Main(string[] args)
{
int i, j, m, n, sum = 0; int count = 0; Console.Write("The MxN matrix\n"); Console.Write("Enter the number of rows and columns of the matrix :\n"); Console.Write("Rows (M): "); m = Convert.ToInt32(Console.ReadLine()); Console.Write("Columns (N): "); n = Convert.ToInt32(Console.ReadLine()); int[,] arr = new int[m, n]; Console.Write("Enter elements in the first matrix :\n");
/* Entering matrix elements */
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
{
Console.Write("element - [{0}],[{1}] : ", i, j);
arr[i, j] = Convert.ToInt32(Console.ReadLine());
/* Calculating odd numbers of the matrix */
if (arr[i, j] % 2 != 0)
{
sum += arr[i, j];
}
}
}
Console.Write("\nThe matrix is:\n");
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
Console.Write("{0} ", arr[i, j]);
Console.Write("\n");
}
Console.Write("\nThe sum of odd numbers is: {0}", sum);
/* Sorting Matrix in ascending order*/
for (i = 0; i < arr.Length - 1; i++)
{
for (j = i + 1; j < arr.Length; j++)
{
int row1 = i % m;
int col1 = i / m;
int row2 = j % m;
int col2 = j / m;
if (arr[row1, col1] > arr[row2, col2])
{
int temp = arr[row1, col1];
arr[row1, col1] = arr[row2, col2];
arr[row2, col2] = temp;
}
}
}
Console.Write("\nAscending order: ");
for (j = 0; j < n; j++)
{
for (i = 0; i < m; i++)
Console.Write("{0} ", arr[i, j]);
}
Console.Read();
}
}
}

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.

How can I use hopfield network to learn more patterns?

Is there any relation between number of neurons and ability of Hopfield network to recognize patterns?
I write neural network program in C# to recognize patterns with Hopfield network. My network has 64 neurons. When I train network for 2 patterns, every things work nice and easy, but when I train network for more patterns, Hopfield can't find answer!
So, according to my code, how can I use Hopfield network to learn more patterns?
Should I make changes in this code?
There is my train() function:
public void Train(bool[,] pattern)
{
//N is number of rows in our square matrix
//Convert input pattern to bipolar
int[,] PatternBipolar = new int[N, N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
if (pattern[i, j] == true)
{
PatternBipolar[i, j] = 1;
}
else
{
PatternBipolar[i, j] = -1;
}
}
//convert to row matrix
int count1 = 0;
int[] RowMatrix = new int[(int)Math.Pow(N, 2)];
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
RowMatrix[count1] = PatternBipolar[i, j];
count1++;
}
//convert to column matrix
int count2 = 0;
int[] ColMatrix = new int[(int)Math.Pow(N, 2)];
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
ColMatrix[count2] = PatternBipolar[i, j];
count2++;
}
//multiplication
int[,] MultipliedMatrix = new int[(int)Math.Pow(N, 2), (int)Math.Pow(N, 2)];
for (int i = 0; i < (int)Math.Pow(N, 2); i++)
for (int j = 0; j < (int)Math.Pow(N, 2); j++)
{
MultipliedMatrix[i, j] = ColMatrix[i] * RowMatrix[j];
}
//cells in the northwest diagonal get set to zero
for (int i = 0; i < (int)Math.Pow(N, 2); i++)
MultipliedMatrix[i, i] = 0;
// WightMatrix + MultipliedMatrix
for (int i = 0; i < (int)Math.Pow(N, 2); i++)
for (int j = 0; j < (int)Math.Pow(N, 2); j++)
{
WeightMatrix[i, j] += MultipliedMatrix[i, j];
}
And there is Present() function (this function is used to return answer for a given pattern):
public void Present(bool[,] Pattern)
{
int[] output = new int[(int)(int)Math.Pow(N, 2)];
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
OutputShowMatrix[i, j] = 0;
}
//convert bool to binary
int[] PatternBinary = new int[(int)Math.Pow(N, 2)];
int count = 0;
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
if (Pattern[i, j] == true)
{
PatternBinary[count] = 1;
}
else
{
PatternBinary[count] = 0;
}
count++;
}
count = 0;
int activation = 0;
for (int j = 0; j < (int)Math.Pow(N, 2); j++)
{
for (int i = 0; i < (int)Math.Pow(N, 2); i++)
{
activation = activation + (PatternBinary[i] * WeightMatrix[i, j]);
}
if (activation > 0)
{
output[count] = 1;
}
else
{
output[count] = 0;
}
count++;
activation = 0;
}
count = 0;
for (int j = 0; j < N; j++)
for (int i = 0; i < N; i++)
{
OutputShowMatrix[i, j] = output[count++];
}
In below images I trained Hopfield for characters A and P and when input patterns are like A or P, network recognize them in true way
Then I train it for character C:
This is where every things go wrong!
Now if I enter pattern like C, this issue happen:
And if enter pattern like A, see what happen:
And if train more patterns, whole of grid become black!
I've spotted only one mistake in your code: you perform only one iteration of node value calculation, without verifying if the values have converged. I've fixed this method like this:
public bool[,] Present(bool[,] pattern)
{
bool[,] result = new bool[N, N];
int[] activation = new int[N * N];
int count = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
activation[count++] = pattern[i, j] ? 1 : 0;
}
bool convergence = false;
while (!convergence)
{
convergence = true;
var previousActivation = (int[])activation.Clone();
for (int i = 0; i < N * N; i++)
{
activation[i] = 0;
for (int j = 0; j < N * N; j++)
{
activation[i] += (previousActivation[j] * WeightMatrix[i, j]);
}
activation[i] = activation[i] > 0 ? 1 : 0;
if (activation[i] != previousActivation[i])
{
convergence = false;
}
}
}
count = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
result[i, j] = activation[count++] == 1;
}
return result;
}
This slightly improves the results, however probably should also be improved to calculate the values asynchronously to avoid cycles.
Unfortunately, this still introduces the behaviour you've described. This is results from the phenomena called spurious patterns. For the network to learn more than one pattern consider training it with a Hebb rule. You can read about the spurious patterns, stability and learning of the Hopfield network here and here.

C# Multiplication Table

So I'm attempting to print a multiplication table in C# however I can't quite figure out how to get what I need.
So far my program outputs the following:
1 2 3
2 4 6
3 6 9
However, I need it to output this:
0 1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
I've tried a lot of different ways to get the second output however I can't quite figure it out. I'm not necessarily asking for an answer but if someone could point me in the right direction it would be much appreciated.
This is the code I have as of now:
static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write(i * j + "\t");
}
Console.Write("\n");
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
Console.Write(i + "\t");
for (int j = 1; j <= 3; j++)
{
if (i>0) Console.Write(i * j + "\t");
else Console.Write(j + "\t");
}
Console.Write("\n");
}
int tbl= int.Parse(Console.ReadLine());
int j = int.Parse(Console.ReadLine());
for (int i=1; i<=10; i++)
{
for (int j=1;j<=10; j++)
{
Console.WriteLine("{0}*{1}={2}", i, j, (i * j));`enter code here`
}
}
Console.ReadLine();
You should skip both 0's.
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
Console.Write((i == 0? j : (j == 0? i : i*j)) + "\t");
}
Console.Write("\n");
}
You could try one of this three solutions.
Solution 1 (without if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
Console.Write("{0}\t", i);
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 2 (With if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (i == 0)
{
Console.Write("{0}\t", i);
}
else
{
Console.Write("{0}\t", i * j);
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Solution 3 (With short-hand if else statement):
static void Main(string[] args)
{
for (int i = 0; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
Console.Write("{0}\t", (i == 0) ? i : i * j);
}
Console.WriteLine();
}
Console.ReadLine();
}
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
if (i == 0)
{
Console.Write(j);
}
else
{
if(j == 0)
{
Console.Write(i);
}
else
{
Console.Write(i * j);
}
}
}
Console.Write("\n");
}
Console.WriteLine("Enter A Number");
int j = Convert.ToInt32(Console.ReadLine());
for (int i = 0 ; i <= 10; i++) {
Console.WriteLine("{1} X {0} = {2}",i,j,i*j);
Console.ReadLine();
}
public class Program
{
//int num;
public static void Main(string[] args)
{
int num,num1;
Console.WriteLine("enter a any number num");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter any second number num1");
num1 = Convert.ToInt32(Console.ReadLine());
for(int i = num;i <= num1; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write(i *j+ "\t");
}
}
Console.Write("\n");
}
}
using System;
/*
* Write a console-based application that displays a multiplication table of the product of
* every integer from 1 through 10 multiplied by every integer from 1 through 10. Save the
* file as DisplayMultiplicationTable.cs.
*/
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\t\t\t\t\t\t\t\tMultiplication Table");
Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------------");
const int END = 11;
for(int x = 1; x < END; x++)
{
for(int y = 1; y < END; y++)
{
int value = x * y;
Console.Write("{0} * {1} = {2}\t", y, x, value);
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
Output
Output of Code
I am attempting to complete the above code in a GUI. So far I have come up with the following code; but the output is not like the above output.
My Code for the GUI is as follows:
using System;
using System.Windows.Forms;
namespace DisplayMultiplicationTableGUI
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}
private void ShowTableButton_Click(object sender, EventArgs e)
{
int a;
int b;
const int STOP = 11;
for(a = 1; a < STOP; a++)
{
for(b = 1; b < STOP; b++)
{
int value = a * b;
multiplicationTableLabel.Text += String.Format("{0} * {1} = {2} ", b, a, value);
}
multiplicationTableLabel.Text += "\n";
}
}
}
}

Categories

Resources