Calculating Mahalanobis distance with C# - c#

I'm trying to calculate the mahalanobis distance with c#. I can't find any real good examples online and I'm new to C#. I am especially having trouble getting the covariance matrix to run right. Any help would be appreciated. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra.Double;
namespace MahalanobisDistance
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
DenseVector vector1 = new DenseVector(4);
DenseVector vector2 = new DenseVector(4);
DenseMatrix matrix1 = new DenseMatrix(vector1.Count/2);
vector1[0] = 1;
vector1[1] = 2;
vector1[2] = 3;
vector1[3] = 4;
vector2[0] = 2;
vector2[1] = 12;
vector2[2] = 14;
vector2[3] = 18;
matrix1 = p.twoPassCovariance(vector1, vector2);
for(int i = 0; i < matrix1.RowCount; i++)
{
for(int k = 0; k < matrix1.ColumnCount; k++)
{
Console.Write(matrix1[k, i] + " ");
}
//Mahalanobis2(v1, v2, covariance);
Console.Write("\n");
}
}
public DenseMatrix twoPassCovariance(DenseVector data1, DenseVector data2)
{
int n = data1.Count;
double mean1 = data1.Average();
double mean2 = data2.Average();
DenseMatrix covariance = new DenseMatrix(data1.Count);
double x;
for(int i = 0; i < 2; i++)
{
for (int k = 0; k < n; k++)
{
double a = data1[i] - mean1;
double b = data2[k] - mean2;
x = a*b;
covariance[i, k] = x;
}
}
covariance.Multiply(1/n);
return covariance;
}
}}

In the i loop in the twoPassCovariance method, I believe you should loop to i < n rather than i < 2.

Related

Why can't get matrix what I passed to Thread?

I want to do some basic stuff: get a matrix, and iterate on it with multiple threads. For example, if I have a 20x20 sized matrix, and I have 4 threads, then the first Thread have to iterate on the 5x20 sized matrix, the second one has to iterate on the same size, but from the 6th row to the 10th one, and so on. But, my program gets only the first part, the second, and third, fourth threads can't see their submatrixes. Why? Can anyone help me with this?
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace multi_thred_test
{
class thredData
{
public int my_simulation_size;
public int[,] my_simulation;
public string my_path;
public int my_nrOfAvailableThreads;
public int my_oneThreeadSubsimulationSize;
public thredData(ref int simsize, ref int[,] simu, ref string path, ref int availabelthrd, ref int subsimsize )
{
my_simulation_size = simsize;
my_simulation = new int[simsize, simsize];
for (int i = 0; i < simsize; i++)
{
for (int j = 0; j < simsize; j++)
{
my_simulation[i, j] = simu[i, j];
}
}
my_path = path;
my_nrOfAvailableThreads = availabelthrd;
my_oneThreeadSubsimulationSize = subsimsize;
}
}
class Program
{
public static int simulation_size = 20;
public static int[,] simulation = new int[20, 20];
public static string path = Directory.GetCurrentDirectory();
public static int nrOfAvailableThreads = Environment.ProcessorCount;
public static int oneThreeadSubsimulationSize = simulation_size / nrOfAvailableThreads;
public static thredData tmp;
public static void Main(string[] args)
{
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
simulation[idx, jdx] = idx * 100 + jdx;
}
}
StreamWriter sw = new StreamWriter(path + "_matrix.txt");
for (int idx = 0; idx < simulation_size; idx++)
{
for (int jdx = 0; jdx < simulation_size; jdx++)
{
sw.Write(simulation[idx, jdx]+" ");
}
sw.WriteLine(" ");
}
sw.Close();
tmp = new thredData(ref simulation_size, ref simulation, ref path, ref nrOfAvailableThreads, ref oneThreeadSubsimulationSize);
//generate threads
for (int thrdnr = 0; thrdnr < nrOfAvailableThreads; thrdnr++)
{
Thread newThread = new Thread(ThreadMethod);
newThread.Name = Convert.ToString(thrdnr);
newThread.Start();
}
Console.ReadKey();
}
private static void ThreadMethod()
{
Thread thr = Thread.CurrentThread;
int simulationSize = Convert.ToInt32(thr.Name);
int thrd_simulation_size;
int[,] thrd_simulation;
string thrd_path;
int thrd_nrOfAvailableThreads;
int thrd_oneThreeadSubsimulationSize;
lock (tmp)
{
thrd_simulation_size = tmp.my_simulation_size;
thrd_simulation = new int[thrd_simulation_size, thrd_simulation_size];
for (int i = 0; i < tmp.my_simulation_size; i++)
{
for (int j = 0; j < tmp.my_simulation_size; j++)
{
thrd_simulation[i, j] = tmp.my_simulation[i, j];
}
}
thrd_path = tmp.my_path;
thrd_nrOfAvailableThreads = tmp.my_nrOfAvailableThreads;
thrd_oneThreeadSubsimulationSize = tmp.my_oneThreeadSubsimulationSize;
}
for (int i = thrd_simulation_size * simulationSize; i < thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name +":"+ thrd_simulation[i,j] + " ");
}
Console.Write("\n");
}
}
}
}
Problem solved, the log part was wrong:
for (int i = thrd_oneThreeadSubsimulationSize * simulationSize; i < (thrd_oneThreeadSubsimulationSize * simulationSize) +thrd_oneThreeadSubsimulationSize; i++)
{
for (int j = 0; j < thrd_simulation_size; j++)
{
Console.Write(thr.Name + ":" + thrd_simulation[i, j] + " ");
}
Console.Write("\n");
}

C#: How do I add all values in the column of an array into one box. XNA 3D

I am trying to simulate how gravity acts on objects in space using 3D xna programming (for a school project). I am calculating the direction and velocities of each of the objects in relation to each other object and turning this into an array of movements. I am then trying to sum up all the movement of each object into one Vector3 and storing this in a one dimensional array. I am able to add up all the movements apart from the last index value in the array.
This is my Gravitation class
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace GravitySimulator
{
class Gravitation
{
static Random Random = new Random();
public Vector3[] positions = new Vector3[3], summovement = new Vector3[3];
public float[,] distance = new float[3, 3], force = new float[4, 4], acceleration = new float[3, 3], velocity = new float[3, 3];
public Vector3[,] dir = new Vector3[3, 3], movement = new Vector3[3, 3];
public double G, mass;
public void GenerateVectors()
{
for (int vectors = 0; vectors < positions.Length; vectors++)
{
positions[vectors] = new Vector3(Random.Next(-7, 7), Random.Next(-12, 12), Random.Next(-5, 5));
}
}
public void CalculateDistance()
{
for (int j = 0; j < positions.Length; j++)
{
for (int i = 0; i < positions.Length; i++)
{
distance[j, i] = Vector3.Distance(positions[j], positions[i]);
}
}
}
public void CalculateForce()
{
G = 6.67 * Math.Pow(10, -11);
mass = 1;
for (int k = 0; k < positions.Length; k++)
{
for (int l = 0; l < positions.Length; l++)
{
force[k, l] = (float)((G * mass * mass) / Math.Pow(distance[k, l], 2));
}
}
}
public void CalulateAcceleration()
{
for (int m = 0; m < positions.Length; m++)
{
for (int n = 0; n < positions.Length; n++)
{
acceleration[m, n] = (float)(force[m, n] / mass);
}
}
}
public void SummariseMovement()
{
for (int a = 0; a < positions.Length; a++)
{
for (int b = 0; b < positions.Length;b++)
{
summovement[a] = movement[a, b];
}
}
}
}
}

How to arrangement of points on the chart in checker

I'm trying to make a chart in checkerboard (as pictured in the screenshot), but I can not think of an algorithm for its construction. How can I change my algorithm so that I can build it?
// location for the first point
double x = FirstStationX;
double y = FirstStationY;
double x1 = 0, y1 = 0;
// button separation inline
double spacingX = InlineStations * (InlineSpacing - 1);
// button separation crossline
double spacingY = CrosslineStations * (CrosslineSpacing - 1);
// Cycle by number of blocks (buttons) along the X axis
for (int i = 0; i < InlineButtons; i++)
{
if (i > 0) x = x1 + spacingX + InlineSeparation;
// Cycle by number of blocks (buttons) along the Y axis
for(int j = 0; j < CrosslineButtons; j++)
{
if (j > 0)
{
y = y1 + spacingY + CrosslineSeparation;
}
// Cycle by number of point in buttons along the X axis
for(int k = 0; k < InlineStations; k++)
{
if (k == 0) x1 = x;
else x1 = x1 + InlineSpacing;
// Cycle by number of point in buttons along the Y axis
for(int h = 0; h < CrosslineStations; h++)
{
if (h == 0) y1 = y;
else y1 = y1 + CrosslineSpacing;
listPointsButtonStation.Add(new ObservablePoint(x1, y1));
}
}
}
}
Try code like this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication26
{
public partial class Form1 : Form
{
const string IMAGE_FILENAME = #"c:\temp\image1.jpg";
const int NUMBER_OF_CHART_COLUMNS = 8;
const int NUMBER_OF_CHART_ROWS = 8;
const int MAIN_PANEL_TOP = 20;
const int MAIN_PANEL_LEFT = 20;
const int MAIN_PANEL_WIDTH = 1000;
const int MAIN_PANEl_HEIGHT = 1000;
const int CHART_LEFT = 20;
const int CHART_TOP = 20;
const int CHART_WIDTH = 100;
const int CHART_HEIGHT = 100;
const int CHART_SPACE = 10;
List<MyChart> charts = new List<MyChart>();
public Form1()
{
InitializeComponent();
Panel mainPanel = new Panel();
mainPanel.Left = MAIN_PANEL_LEFT;
mainPanel.Top = MAIN_PANEL_TOP;
mainPanel.Height = MAIN_PANEl_HEIGHT;
mainPanel.Width = MAIN_PANEL_WIDTH;
this.Controls.Add(mainPanel);
for(int row = 0; row < NUMBER_OF_CHART_ROWS; row++)
{
for (int col = 0; col < NUMBER_OF_CHART_COLUMNS; col++)
{
MyChart newChart = new MyChart();
newChart.row = row;
newChart.col = col;
newChart.Width = CHART_WIDTH;
newChart.Height = CHART_HEIGHT;
newChart.Left = col * (CHART_WIDTH + CHART_SPACE);
newChart.Top = row * (CHART_HEIGHT + CHART_SPACE);
newChart.Image = Image.FromFile(IMAGE_FILENAME);
mainPanel.Controls.Add(newChart);
charts.Add(newChart);
}
}
}
}
public class MyChart : PictureBox
{
public int row { get; set; }
public int col { get; set; }
}
}

Series problems forloop

i have a problem in my series number that will output the 1,2,4,7,11 and etc. i have my forloop that handle the 0,1,2,3,4,5 but im having trouble to progress the 1,2,4,7,11 output please help me this is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int v = 0; v <= 5; v++)
{
for (int x = 1; x <= 5; x++)
{
int c = v + x;
}
}
Console.ReadKey();
}
}
}
ok try this...
class Program
{
static void Main(string[] args)
{
int c = 1;
for (int v = 0; v <= 5; v++)
{
c = c + v;
Console.Write("{0} ", c);
}
Console.ReadKey();
}
}
I hope it will help you...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var iterations = 50;
var result = 0;
for (int i = 0; i < iterations; i++)
{
result += i;
}
Console.WriteLine(result);
Console.ReadKey();
}
}
}
You can try this to control number to calculate from console not by code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number to calculate: ");
int num = Convert.ToInt32(Console.ReadLine());
Fib(0, 1, 1, num);
}
public static void Fib(int i, int j, int count, int num)
{
Console.WriteLine(i);
if (count < num) Fib(j, i+j, count+1, num);
}
I got it.
int x = 1;
for (int v = 0; v <= 5; v++)
{
int c = x + v;
x = c;
Console.Write(c);
}
Console.ReadKey();
It seems something like this :
var f1 = 0;
var f2 = 1;
for (int i = 1; i < 7; i++)
{
Console.WriteLine(f1);
f1 = f2;
f2 = f2 + i;
}
Output :
0, 1, 2, 4, 7, 11
This should work.
int i=1;
int j=0;
while(i<50)
{
i+=j;
j+=1;
Console.Writeln(i)
}
I hope , it should be solve the problem
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace While_loop
{
class Program
{
static void Main(string[] args)
{
int i = 1;
Console.WriteLine(i);
while (i < 10)
{
for (int j = 1; j < 5; j++)
{
i = i + j;
Console.WriteLine(i);
}
i++;
}
Console.ReadKey();
}
}
}

Combining arrays created via multiple threads

I have been trying to create couple of 2-D arrays via multi-threading. Each threading will generate a small 2-D array. All of the 2-D will be consolidated and that is where I am having issue. I commented "//!this is causing error" towards the bottom of SimulatingMethod method. Please share your insight. Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadExample
{
class Program
{
static void Main(string[] args)
{
double[,] randSims;
randSims = SimulatingClass.SimulatingMethod();
}
}
class SimulatingClass
{
public static double[,] SimulatingMethod()
{
int rowCount = 9;
int columnCount = 1;
int NumberOfCores = System.Environment.ProcessorCount;
int RowsForEachThread = rowCount / NumberOfCores;
Thread[] arrayOfThread = new Thread[NumberOfCores];
DataStuff[] dataStuff= new DataStuff[NumberOfCores];
for (int i = 0; i < NumberOfCores; i++)
{
dataStuff[i] = new DataStuff(RowsForEachThread, columnCount);
arrayOfThread[i] = new Thread(new ThreadStart(dataStuff[i].UpdateMatrixData));
arrayOfThread[i].Name = "Thread" + i;
arrayOfThread[i].Start();
}
for (int i = 0; i < NumberOfCores; i++)
{
arrayOfThread[i].Join();
}
//start combining arrays from different threads
var list = new List<double[,]>();
for (int m = 0; m < NumberOfCores; m++)
{
list.AddRange(dataStuff[m]); //!this is causing error
}
//trying to convert list back to array
double[,] array3 = list.ToArray(); //!this is causing error
return array3;
}
}
class DataStuff
{
public double G;
public double[,] M;
public long steps, trials;
public DataStuff(long _steps, long _trials)
{
M = new Double[_steps, _trials]; // <- M is created in the constructor
G = 60;
steps = _steps;
trials = _trials;
}
public void UpdateMatrixData()
{
for (int i = 0; i < steps; i++)
{
for (int j = 0; j < trials; j++)
{
M[i, j] = i + j;
}
}
}
}
}
You should specify the property as follows:
list.Add(dataStuff[m].M);
It's because the dataStuff[m] is of type DataStuff, but the type double[,] expected as the list item.
If I understood you correctly, you need a consolidated 2D array. Try to declare it initially with desired dimensions:
double[,] array3 = new double[rowCount, columnCount];
And copy data from dataStuff array to it after processing:
for (int m = 0; m < NumberOfCores; m++)
{
Array.Copy(dataStuff[m].M, 0, array3, m * columnCount * RowsForEachThread, dataStuff[m].M.Length);
}
return array3;
And you don't need list at all.
Please note, that you have possible problems related to the rounding:
int RowsForEachThread = rowCount / NumberOfCores;
You should handle the situation when the rowCount is not divisible by the NumberOfCores.

Categories

Resources