Average of of 2 coordinates - c#

So I am making a graph of the average between to lists of coordinates.
So I have been looking all over and can't seem to find any information on how I can find the average of the 2 lists of values. When I try I get an error "the index was outside the matrix boundaries" and when I got it to work I just made a graph where the years where extremely high and the graph itself were looking insane. What i do is importing 2 parts of(data/data2) information with Json.
//
// Data
//
int tal = dataSet.dataset.value.Count;
//Add items in the listview
int[] yData = new int[tal];
int[] xData = new int[tal];
int k = 0;
foreach (var item in dataSet.dataset.dimension.Tid.category.label)
{
xData[k++] = int.Parse(item.Value.ToString());
}
for (int i = 0; i < tal; i++)
{
yData[i] = dataSet.dataset.value[i];
}
//
// Data2
//
int tal2 = dataSet2.dataset.value.Count;
int[] y2Data = new int[tal2];
int[] x2Data = new int[tal2];
int j = 0;
foreach (var item in
dataSet2.dataset.dimension.Tid.category.label)
{
x2Data[j++] = int.Parse(item.Value.ToString());
}
for (int p = 0; p < tal2; p++)
{
y2Data[p] = dataSet2.dataset.value[p];
}
This is the part
///////////////////////////////////////////////////////////
int[] ySum = new int[xData.Length];
for (int i = 0; i < xData.Length; i++)
{
ySum[i] = (yData[i] + y2Data[i]) / 2;
}
///////////////////////////////////////////////////////////
List<int> GenUd = new List<int>(yData.ToList());
textBoxGenUd.Text = GenUd.Average().ToString();
List<int> GenInd = new List<int>(y2Data.ToList());
textBoxGenInd.Text = GenInd.Average().ToString();
chartArea1.Name = "ChartArea1";
chart2.ChartAreas.Add(chartArea1);
chart2.Dock = DockStyle.Fill;
for (int i = 0; i <xData.Count(); i++)
{
series1.Points.AddXY(ySum[i], x2Data[i]);
}
MySecChart2 mc3 = new MySecChart2(series1);
mc3.ShowDialog();

mine is just an educated guess - if the exception occurs at the following:
This is the part
///////////////////////////////////////////////////////////
int[] ySum = new int[xData.Length];
for (int i = 0; i < xData.Length; i++)
{
ySum[i] = (yData[i] + y2Data[i]) / 2;
}
///////////////////////////////////////////////////////////
My diagnosis would be that yData[i] and y2Data[i] they dont have the same length and of xData.Length define into the loop definition.
Was perhaps supposed to be yData.Length in the loop definition?

Related

2d_array random numbers (10Rows, 6 COLS) not repeated to file C#

I need to streamwrite into a file.txt a 10 random numbers combinations (NOT REPEATED) like lottery program. I got everything except Non-repeated random numbers. it has to be seen (file.txt) like a 2D array with 10 combinations thx.
class Matriz
{
private int[,] array;
private int nfilas, ncols;
public void Ingresar()
{
Random aleatori = new Random();
nfilas = 10;
ncols = 6;
Console.WriteLine("\n");
array = new int[nfilas, ncols];
for (int filas = 0; filas < nfilas; filas++)
{
for (int columnas = 0; columnas < ncols; columnas++)
array[filas, columnas] = aleatori.Next(0, 50);
}
}
public void Imprimir()
{
StreamWriter fitxer = new StreamWriter(#"C:\andres\lotto649.txt");
int contador = 0;
for (int f = 0; f < nfilas; f++)
{
for (int c = 0; c < ncols; c++)
fitxer.Write(array[f, c] + " ");
fitxer.WriteLine();
contador++;
}
fitxer.WriteLine($"\n\n\tHay {contador} combinaciones de la Loteria 6/49");
fitxer.Close();
}
static void Main(string[] args)
{
Matriz array_menu = new Matriz();
array_menu.Ingresar();
array_menu.Imprimir();
}
}
Something like this should work.
Before inserting the new number in the given position, check the row thus far if the same number is already in there and if so, repeat the process until you get a number that isn't yet in there.
for (int filas = 0; filas < nfilas; filas++)
{
for (int columnas = 0; columnas < ncols; columnas++)
{
bool cont = true;
while(cont)
{
cont = false;
int newRand = aleatori.Next(0, 50);
for(int i = 0; i < columnas; i++)
if(array[filas, i] == newRand)
cont = true;
if(cont)
continue;
array[filas, columnas] = newRand;
break;
}
}
}
Alternatively, since the number is small you could also work with a list of ints and remove the given value from there.
This has the advantage, that you'll never have to redo your random number as it will always produce a valid result. The above example could (theoretically) run indefinitely long.
for (int filas = 0; filas < nfilas; filas++)
{
List<int> nums = new List<int>(49);
for(int i = 0; i < 49; i++)
nums.Add(i + 1); //num 1...49
for (int columnas = 0; columnas < ncols; columnas++)
{
int index = aleatori.Next(0, nums.Count)
array[filas, columnas] = nums[index];
nums.RemoveAt(index);
}
}

sum middle number with jagged array in C#

I write some code with jagged array but when i sum middle number program not working and i cant fix it...:
public class JaggedArray
{
public static void Array()
{
int[][] arrayOfArray = ArrayOfArray();
var tong = 0;
for (var i = 1; i < arrayOfArray.Length; i++)
{
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
var bienTam = arrayOfArray[i].Length;
var tamThoi = j;
if (bienTam%2==0&&tamThoi==bienTam/2)
{
tamThoi++;
tong += arrayOfArray[i][tamThoi];
}
}
}
OutPut(arrayOfArray, tong);
}
private static int[][] ArrayOfArray()
{
Random ngauNhien = new Random();
int[][] arrayOfArray = new int[13][];
for (var i = 0; i <arrayOfArray.Length; i++)
{
arrayOfArray[i] = new int[i];
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
arrayOfArray[i][j] = ngauNhien.Next(0, 99); //throw exception
}
}
return arrayOfArray;
}
can someone explain reason why i wrong and how ti fix it?
The problem you are solving is the one Linq is very good for:
int[][] arrayOfArray = new int[][] {
new[] {1, 2, 3}, // 2 is the middle item
new[] {4, 5} // in case of tie, let 5 (right) be the middle item
new[] {7}, // 7
new int[] {}, // should be ignored
};
// 2 + 5 + 7 == 14
var result = arrayOfArray
.Where(line => line != null && line.Length > 0)
.Sum(line => line[line.Length / 2]);
So I've got it compiling:
public class JaggedArray
{
public static void Array()
{
int[][] arrayOfArray = ArrayOfArray();
var tong = 0;
for (var i = 1; i < arrayOfArray.Length; i++)
{
for (var j = 0; j < arrayOfArray[i].Length; j++)
{
var bienTam = arrayOfArray[i].Length;
var tamThoi = j;
if (j % 2 == 0 && j / 2 == bienTam / 2)
{
tamThoi++;
// You need to check here that tamThoi isn't
// outside the bounds of your array
if (tamThoi >= arrayOfArray[i].Length)
{
continue;
}
tong += arrayOfArray[i][tamThoi];
}
}
}
}
private static int[][] ArrayOfArray()
{
Random ngauNhien = new Random();
int[][] arrayOfArray = new int[13][];
for (var i = 0; i < 13; i++)
{
arrayOfArray[i] = new int[i];
// here you're better off using i
// instead of the arrayOfArray[i].Length - because you know the length
for (var j = 0; j < i; j++)
{
arrayOfArray[i][j] = ngauNhien.Next(0, 99);
}
}
return arrayOfArray;
}
}
You can make this far more succinct with LINQ.

C# - Access a one slice of a multi-dimensional array

Suppose a have a MxNx3 matrix
byte [,,] myMatrix= new byte[sizeRow, sizeCol, 3];
How do I access a single band of it (for read and write purposes)? Something like:
singleBand = myMatrix[:allRows: , :allCols: , :desiredBand:];
On the left is what I have, of the right is what I want to access (for example).
int M=10;
int N=20;
var test = new byte[3][,] { new byte[N,M],new byte[N,M],new byte[N,M]};
var band1 = test[1]; //its green
band1[2, 2] = 99;
If you can't change the type of myMatrix, then you can use the following code:
byte [,,] myMatrix= new byte[sizeRow, sizeCol, 3];
var singleBand = new byte[sizeRow, sizeCol];
var band = 1;
for (var i = 0; i < sizeRow; i++) {
for (var j = 0; j < sizeCol; j++) {
singleBand[i, j] = myMatrix[i, j, band];
}
}
But if you can change it, then probably Zeromus' solution is better, since you can more easily manipulate with what you call the band.
You simply need to loop through your required array elements and extract the "band" that you need.
// Create a three-dimensional array.
int[, ,] threeDimensional = new int[3, 3, 3];
// Set the first "Band" to 9
threeDimensional[0,0,1] = 9;
threeDimensional[1,0,1] = 9;
threeDimensional[2,0,1] = 9;
threeDimensional[0,1,1] = 9;
threeDimensional[1,1,1] = 9;
threeDimensional[2,1,1] = 9;
threeDimensional[0,2,1] = 9;
threeDimensional[1,2,1] = 9;
threeDimensional[2,2,1] = 9;
// Loop over each dimension's length.
for (int i = 0; i < threeDimensional.GetLength(2); i++)
{
for (int y = 0; y < threeDimensional.GetLength(1); y++)
{
for (int x = 0; x < threeDimensional.GetLength(0); x++)
{
Console.Write(threeDimensional[x, y, i]);
}
Console.WriteLine();
}
Console.WriteLine();
}
Your only option is to access each "cell" in the band one at a time and extract it to some other location. In my case i just put them out to the display.

Hiding an array picturebox c#

This generates a picturebox
PictureBox[][] picturebox;
public void loadPictureBox()
{
string path = #"../../Images/Catelogue/"; //set pathing
string[] list = Directory.GetFiles(path, "*.jpg");
//pictureboxCatelogue = new PictureBox[list.Length];
//pictureboxCosplay = new PictureBox[list.Length];
picturebox = new PictureBox[4][];
for (int i = 0; i < 4; i++)
{
picturebox[i] = new PictureBox[list.Length];
int y = 85, temp = 220, run = 0;
for (int index = 13; index < list.Length; index++) // loads all pictures and create pictureboxes
{
picturebox[i][index] = new PictureBox();
picturebox[i][index].Image = Image.FromFile(path + index + ".jpg");
this.Controls.Add(picturebox[i][index]);
temp = temp + 200;
if (index % 4 == 0)
{
if (run != 0)
y = y + 200;
run++;
temp = 220;
}
picturebox[i][index].Location = new Point(temp, y);
picturebox[i][index].Size = new Size(180, 180);
picturebox[i][index].Name = Convert.ToString(index);
picturebox[i][index].SizeMode = PictureBoxSizeMode.Zoom;
picturebox[i][index].BackColor = Color.FromArgb(35, 35, 35);
picturebox[i][index].Click += new System.EventHandler(PictureBox_Click);
}
}
}
I'm trying to hide a jagged array which is a picturebox in winsform c#, but i keep getting an error, is hiding a jagged array possible? This is the code that i'm having trouble with.
for (int i = 0; i < picturebox.Length; i++)
{
picturebox[0][i].Hide();
}
This is the error i get
ERROR : A first chance exception of type 'System.NullReferenceException' occurred in APPD Assignment 2.exe (Additional information: Object reference not set to an instance of an object.)
Aren't you using the wrong length here?
for (int i = 0; i < picturebox.Length; i++)
Should be
for (int i = 0; i < picturebox[0].Length; i++)
When you load the pictureboxes, you're only starting at index 13, so you either need to start the hide loop at 13, or check for null.
for (int i = 13; i < picturebox[0].Length; i++)
{ ... }
or
for (int i = 0; i < picturebox[0].Length; i++)
{
if (picturebox[0][i] != null)
{
picturebox[0][i].Hide();
}
}

Encog 3.3 library for c#: I get a 0.79 error on my network but does not improve

Im new at programming, and I am trying to learn Encog 3.3 Library. I worked on making my first network. I was able to write and understand the Code; However, My error rate does not go below 0.79, I used TANH activation function. My network is suppose to return 1 of three values -1,0,1 based on a set of variables I input it. Has anyone Have this same Problem?
this is the Code:
static void Main(string[] args)
{
// creating the neural net : network
var network = new BasicNetwork();
network.AddLayer(new BasicLayer(null, true,21));
network.AddLayer(new BasicLayer( new ActivationTANH(), true,15));
network.AddLayer(new BasicLayer(new ActivationTANH(), true, 15));
network.AddLayer(new BasicLayer(new ActivationTANH(), true,1));
network.Structure.FinalizeStructure();
network.Reset();
// creating the training Data
string Path = "";
var listArray = GetFile(Path);
int amountNumbersY = GetYSize(listArray);
int amountNumbers = GetXSize(listArray[1]);
string[,] matrixString = new string[listArray.Length, amountNumbers]; matrixString = splitter(listArray, amountNumbers);
double[][] allData = new double[amountNumbers][];
for (int i = 0; i < allData.Length; i++)
allData[i] = new double[amountNumbersY];
allData = ConvertToDouble(matrixString, amountNumbers);
// creating the inpuit and output
double[][] XOR_INPUT = new double[amountNumbersY][];
for (int i = 0; i < amountNumbersY; i++)
{
XOR_INPUT[i] = new double[amountNumbers - 1];
}
double[][] XOR_IDEAL = new double[amountNumbersY][];
for (int i = 0; i < amountNumbersY; i++)
{
XOR_IDEAL[i] = new double[1];
}
XOR_INPUT = GetInput(allData, amountNumbers, amountNumbersY, 1);
XOR_IDEAL = GetIdealOutPut(allData, amountNumbers, amountNumbersY, 1);
// normalizing the Arrays
double[][] temp_Input = new double[amountNumbersY-1][];
for (int i = 0; i < amountNumbersY-1; i++) // initializing the x axis
{
temp_Input[i] = new double[amountNumbers - 1];
}
double[][] temp_Ideal = new double[amountNumbersY-1][]; // same as above for output matrix
for (int i = 0; i < amountNumbersY-1; i++)
{
temp_Ideal[i] = new double[1];
}
double[][] closedLoop_temp_Input = new double[amountNumbersY-1][];
for (int i = 0; i < amountNumbersY-1; i++) // initializing the x axis
{
closedLoop_temp_Input[i] = new double[amountNumbers - 1];
}
double[][] closedLoop_temp_Ideal = new double[amountNumbersY-1][];
for (int i = 0; i < amountNumbersY-1; i++)
{
closedLoop_temp_Ideal[i] = new double[1];
}
var hi = 1;
var lo = -1;
var norm = new NormalizeArray { NormalizedHigh = hi, NormalizedLow = lo };
for (int i = 0; i < amountNumbersY-1; i++)
{
temp_Input[i] = norm.Process( XOR_INPUT[i]);
}
closedLoop_temp_Input = EngineArray.ArrayCopy(temp_Input);
var Ideal_Stats = new NormalizedField(NormalizationAction.Normalize,"Temp_Ideal",1,-1,-1,1);
for (int i = 0; i < amountNumbersY - 1; i++)
{
temp_Ideal[i][0] = Ideal_Stats.Normalize(XOR_IDEAL[i][0]);
}
closedLoop_temp_Ideal = EngineArray.ArrayCopy(temp_Ideal);
IMLDataSet trainingSet = new BasicMLDataSet(closedLoop_temp_Input, closedLoop_temp_Ideal);
// training the network
IMLTrain train = new ResilientPropagation( network, trainingSet);
ICalculateScore score = new TrainingSetScore(trainingSet);
IMLTrain annealing = new NeuralSimulatedAnnealing(network,score,10,2,10);
int epoch = 1;
do
{
if (epoch == 50)
{
int i = 0;
do
{
annealing.Iteration();
Console.WriteLine("Annealing: " + i +", Error: " + annealing.Error);
i++;
} while (i < 5);
}
train.Iteration();
Console.WriteLine(#" Epoch: "+epoch+ #", Error: "+train.Error+"...");
epoch ++;
} while ( train.Error<0.01 || epoch < 1000);
// testing the network
}
}
}
The training rate not falling is one of the most common problems in machine learning. Often it is because the data given to the model simply does not support a prediction. You are training a neural network to predict an output given the input. Consider if you were to train on the following inputs and expected outputs. The data might be noisy or it might be contradictory.
A few suggestions. First, dump your training data to a file and have a look at it. Is it what you expect? Are all of the values between -1 and 1. You have quite a bit of code happening before the training. There could be something going wrong there.
You also have a somewhat hybrid training approach going on, with RPROP and annealing. Perhaps just stick to RPROP and see what happens.

Categories