I'd like to implement something in C# where I could define a multidimensional array and index accordingly or get a specific value by key. Is there a conventional name for this? Or a package for it?
I've implemented in python, but I did a bunch of method overriding to make it work conventionally. There, usage looks like this:
class NamedTicTacToeBoard(VariableMatrix):
def __init__(self):
VariableMatrix.__init__(self)
self.__shape__ = (3, 3)
self.A1 = X
self.A2 = O
self.A3 = X
# and so forth...
board = NamedTicTacToeBoard()
board[0, :]
>> [X, O, X]
board.A1
>> X
Thanks for the help
Edit: I'm not actually making a TicTacToe board, it's for a GNC, so I need to do a bunch of matrix algebra, but also reference the states.
Related
This is my idea to program a simple math module (function) that can be called from another main program. It calculates the FWHM(full width at half the max) of a curve. Since this is my first try at Visual Studio and C#. I would like to know few basic programming structures I should learn in C# coming from a Mathematica background.
Is double fwhm(double[] data, int c) indicate the input arguments
to this function fwhm should be a double data array and an Integer
value? Did I get this right?
I find it difficult to express complex mathematical equations (line 32/33) to express them in parenthesis and divide one by another, whats the right method to do that?
How can I perform Mathematical functions on elements of an Array like division and store the results in the same Array?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DEV_2
{
class fwhm
{
static double fwhm(double[] data, int c) // data as 2d data and c is integer
{
double[] datax;
double[] datay;
int L;
int Mag = 4;
double PP = 2.2;
int CI;
int k;
double Interp;
double Tlead;
double Ttrail;
double fwhm;
L = datay.Length;
// Create datax as index for the number of elemts in data from 1-Length(data).
for (int i = 1; i <= data.Length; i++)
{
datax[i] = (i + 1);
}
//Find max in datay and divide all elements by maxValue.
var m = datay.Length; // Find length of datay
Array.ForEach(datay, (x) => {datay[m++] = x / datay.Max();}); // Divide all elements of datay by max(datay)
double maxValue = datay.Max();
CI = datay.ToList().IndexOf(maxValue); // Push that index to CI
// Start to search lead
int k = 2;
while (Math.Sign(datay[k]) == Math.Sign(datay[k-1]-0.5))
{
k=k+1;
}
Interp = (0.5-datay[k-1])/(datay[k]-datay[k-1]);
Tlead = datax[k-1]+Interp*(datax[k]-datax[k-1]);
CI = CI+1;
// Start search for the trail
while (Math.Sign(datay[k]-0.5) == Math.Sign(datay[k-1]-0.5) && (k<=L-1))
{
k=k+1;
}
if (k != L)
{
Interp = (0.5-datay[k-1])/(datay[k]-datay[k-1]);
Ttrail = datax[k-1] + Interp*(datax[k]-datax[k-1]);
fwhm =((Ttrail-Tlead)*PP)/Mag;
}
}//end main
}//end class
}//end namespace
There are plenty of pitfalls in C#, but working through problems is a great way to find and learn them!
Yes, when passing parameters to a method the correct syntax is MethodName(varType varName) seperated by a comma for multiple parameters. Some pitfalls arise here with differences in passing Value types and Reference types. If you're interested here is some reading on the subject.
Edit: As pointed out in the comments you should write code as best as possible to require as few comments as possible (thus paragraph between #3 and #4), however if you need to do very specific and slightly complex math then you should comment to clarify what is occuring.
If you mean difficulties understanding, make sure you comment your code properly. If you mean difficulties writing it, you can create variables to simplify reading your code (but generally unnecessary) or look up functions or libraries to help you, this is a bit open ended question if you have a particular functionality you are looking for perhaps we could be of more help.
You can access your array via indexes such as array[i] will get the ith index. Following this you can manipulate the data that said index is pointing to in any way you wish, array[i] = (array[i]/24)^3 or array[i] = doMath(array[i])
A couple things you can do if you like to clean a little, but they are preference based, is not declare int CI; int k; in your code before you initialize them with int k = 2;, there is no need (although you can if it helps you). The other thing is to correctly name your variables, common practice is a more descriptive camelCase naming, so perhaps instead of int CI = datay.ToList().IndexOf(maxValue); you coud use int indexMaxValueYData = datay.ToList().IndexOf(maxValue);
As per your comment question "What would this method return?" The method will return a double, as declared above. returnType methodName(parameters) However you need to add that in your code, as of now I see no return line. Such as return doubleVar; where doubleVar is a variable of type double.
After some research I have settled on ILNumerics for a Linear Algebra package in C#.
However I have having some issues working on ranges of the vector. I would like to modify the values in a Vector with a type of moving window, applying a function on the values in this window or range.
Any ideas on how to accomplish this? I cannot find how to do this in the documentation.
This is the kind of operation I would like to do:
ILArray<double> vec = ILMath.array(new [] {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0});
Console.WriteLine(vec);
// create a vector range from index 3-5
var range = vec[2, 5];
Console.WriteLine(range);
// modify all values in range
for (int i = 0; i < range.Length; i++)
range[i] += 10.0;
Console.WriteLine(range);
// view modified original vector
Console.WriteLine(vec);
This will not work, as the range incorrect and the vector cannot be written to using indexing.
Thanks.
I'm a bit unsure if I got this correctly. But you certainly can modify ILArray. Just make sure, you understand the basics for working with ILArray and how to handle the different array types. Especially, prevent from using var in conjunction with ILArray!
Read about the core array features:
http://ilnumerics.net/docs-core.html
Read how to create functions and handle the different ILNumerics array types:
http://ilnumerics.net/GeneralRules.html
I have modified your example. If this is not what you need, please comment on it:
ILArray<double> vec = ILMath.array(new[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 });
Console.WriteLine(vec);
// create a vector range from index 3-5
ILArray<int> range = array<int>(2,3,4,5);
Console.WriteLine(range);
// modify all values in range
for (int i = 0; i < 3; i++) // make tree steps. Modify as needed!
vec[range + i] = vec[range + i] + i;
Console.WriteLine(range);
// view modified original vector
Console.WriteLine(vec);
#Edit: From the comments... this may bring us closer to what you are trying to achieve?
for (int i = 0; i < 3; i++) // make tree steps. Modify as needed!
// dynamic subarrays using ILMath.r()
vec[r(i,i+5)] = vec[r(i,i+5)] + ... ;
Note that you have to use ILMath.r(..) instead of r(..) if your code is not defined in a class which derives from ILMath. Note further that subarray range definitions with r() can be combined with string definitions arbitrarly. This could help to translate it to cases, where matrices or n-dim arrays are involved.
This question already has answers here:
Run F# code in C# - (Like C# in C# using Roslyn)
(3 answers)
Closed 9 years ago.
I was looking for solution to import F# block of code into C# application (in order to gain calculation speed of some operations I have). Therefore I install FSharpx.Core to my C# solution in MS Visual Studio Express 2013.
And that's it...don't know how to continue :-)
Can someone help me with some simple code - e.g. when I click a button in the form, to subtract variable v1 and v2.
Form1.cs
...
private void buttonCalcVars_Click(object sender, EventArgs e)
{
int sum = CallFSharpFunction(1,2);
}
// This should be some F# block of code
private int CallFSharpFunction(int a, int b)
{
let v1 = a;
let v2 = b;
// do some calculations
return result;
}
...
Hope this is possible,
Thank you!
Before using F # one wonders, can you use an F # function in applications written in c #.
Become familiar with functional language F # you can, for example, at this address: http://msdn.microsoft.com/ru-ru/magazine/cc164244.aspx
But here, in my opinion, F # functional language is good for writing various mathematical functions (excuse my tautology), but why take the bread from the object-oriented languages, why put unintelligible code to work with WinForms or WebForms controls pages in F #? Because I immediately wondered how to invoke a function from F # assemblies. Just want to say that because there are difficulties in functional languages with tipizaciâmi when writing code, in the case of using F # functions from C # assemblies these difficulties only increase. Get down to business.
Create a project that includes, for example, the C # console application and an F # Assembly.
F # in the Assembly we need one file MyFunctions. fs. Here we describe some of the features that we believe it is easier for us to write at a functional language. For example, even if it is the translation function array bitmap images from RGB to YCbCr color space (this is just an example). Entry in F # can be roughly this:
open System
let RGB_to_YCbCr (r : double,g : double,b : double) =
let y = 0.299 * r + 0.587 * g + 0.114 * b in
let Cb = (-0.1687) * r - 0.3313 * g + 0.5 * b + 128.0 in
let Cr = 0.5 * r - 0.4187 * g - 0.0813 * b + 128.0 in
(y,Cb,Cr);
let RGB_to_YCbCr_v (v : _ array) =
RGB_to_YCbCr (v.[0], v.[1], v.[2]);
let Process (image : _ array) =
let lenght = Array.length image in
let imageYCbCr = Array.create lenght (0.0, 0.0, 0.0) in
for index = 0 to lenght - 1 do
imageYCbCr.[index] <- RGB_to_YCbCr_v (image.[index])
done
imageYCbCr
After Assembly, we can see that access to features not just have weird views the namespace, and how to use them is not clear. See the location of the functions in the Assembly we can using Reflector.
In order to describe the namespace and the class you need to add the following line immediately after #light:
module FSharp.Sample.MyFunctions
That said, the fact that all the functions written below will contain the class MyFunctions fsharp.Core namespace.
After the project again, we will see that in the Assembly have a clear the fsharp.Core namespace Sample that has the class MyFunctions static methods, which we have described above.
Read more in our console application, we set the Reference to the Assembly the fsharp.core Sample is the name of my Assembly to F # and the fsharp.core -in order to use types (classes) of the F # type Triple. And write the following code:
using System;
using FSharp.Sample;
namespace CSharp.Sample.Console
{
class Program
{
static void Main()
{
double[][] image = new double[1000][];
Random rand = new Random();
for (int i = 0; i < 1000; i ++ )
{
image[i] = new double[3];
image[i][0] = rand.Next();
image[i][1] = rand.Next();
image[i][2] = rand.Next();
}
foreach (var doubles in MyFunctions.Process(image))
{
System.Console.WriteLine(doubles);
}
}
}
}
Where initially we specify to use the fsharp.Core namespace. In the code we generate an array of data and pass it to the function MyFunction. Process, which converts it to the chosen algorithm. We are returned as an array of data types "in Microsoft fsharp.core.. Tuple'3".
Consider a generic complex number:
System.Numerics.Complex z = new System.Numerics.Complex(0,1); // z = i
And now consider the n-th root extraction operation of z. As you all know, when having a problem like z^n = w (having z and w complex numbers and n a positive not null integer) the equation returns n different complex numbers all residing on the complex circle having its radius equal to the module of z (|z|).
In the System.Numerics namespace I could not find such a method. I obviousle need some sort of method like this:
Complex[] NRoot(Complex number);
How can I find this method. Do I really need to implement it myself?
How can I find this method.
You can't, it's not built into the Framework.
Do I really need to implement it myself?
Yes.
Sorry if this comes across as a tad flip, I don't mean to, but I suspect that you already knew this would be the answer.
That said, there's no magic to it:
public static class ComplexExtensions {
public static Complex[] NthRoot(this Complex complex, int n) {
Contract.Requires(n > 0);
var phase = complex.Phase;
var magnitude = complex.Magnitude;
var nthRootOfMagnitude = Math.Pow(magnitude, 1.0 / n);
return
Enumerable.Range(0, n)
.Select(k => Complex.FromPolarCoordinates(
nthRootOfMagnitude,
phase / n + k * 2 * Math.PI / n)
)
.ToArray();
}
}
Most of the work is offloaded to the Framework. I trust that they've implemented Complex.Phase, Complex.Magnitude correctly ((Complex complex) => Math.Sqrt(complex.Real * complex.Real + complex.Imaginary * complex.Imaginary) is bad, Bad, BAD) and Math.Pow correctly.
I know there have been several questions asked relating to interpolation, but I have not found any answers that would be helpful enough for me so I have the following question.
I have two arrays of points. One tracks time (x axis) and one tracks expenses (y axis) and
I want to get something like this:
InterpolatingPolynomial[{{0, 10}, {1, 122}, {2, 3.65}, {3, 56.3}, {4, 12.4}, {5, 0}}, x]
(In Mathematica that returs a constructed polynomial that fits the points). Is it possible, to return a func<double,double> constructed from two double arrays in C#?
Thanks in advance.
This paper describes exactly what you want. The Vandermonde Determinant method is quite simple to implement as it requires to compute the determinant of a matrix in order to obtain the coefficients of the interpolating polynomial.
I'd suggest to build a class with an appropriate interface though, as building Funcs on the fly is pretty complicated (see here for an example). You could do something like:
public class CosineInterpolation {
public CosineInterpolation(double[] x, double[] y) { ... }
public double Interpolate(double x) { ... }
}
I think I found the solution myself after a long day of search. I interpolate a function using Lagrange Interpolation.
A Func<double,double> can be then easily constructed using DLINQ.
e.g
public Func<doube,double> GetFunction()
{
LagrangeInterpolation lagInter = new LagrangeInterpolation(xVals, yVals);
return ( val => lagInter(GetValue(val) );
}
This returns the Func<double,double> object. (I know that creating a new object each time is not a good solution but this is just for demonstrational purposes)