ILNumerics equivalent of MatLab/Octave statement - c#

Question
In MatLab/Octave, I have the statement x(isnan(x)) = 0. I am porting this over to ILNumerics in C#. I am having trouble finding the ILNumerics equivalent to the MatLab/Octave statement mentioned.
In our case, x is a 2x2 array.
What we've tried
noNaNDataValues = dataValues[ILMath.isnan(dataValues)] = 0.0; where dataValues is an ILArray<double>
We have resorted to standard C# for loops and that works fine. But we would rather use ILNumerics considering how much we've invested in it already.

Just use
x[isnan(x)] = 0;
This is directly equivalent to Matlabs syntax. Your first attempt suggests that you want to seperate non-NaN values from NaNs? If so, please clarify.

Related

Doubles precision Values in .NET should match C++

I am currently Debugging a Software that I translated from C++ to C#.
Everything goes fine until one values in C# is different from C++.
the computation is :
v2z = vBlock.z * cos(phi) + v1x * sin(phi);
where
phi = 0.800, vBlock.z =-3.6127196945104552 and v1x= 4.5158996181380688
the result i C++ is
4.4408920985006262e-16
in C# the result is
0
And that is the Problem because in my condition later I need a value v2z >0.
After reading Topics on that subject I found These one interesting Formatting doubles for output in C#.
I thought I could use the DoubleConverter.ToexactString() onto my C# values but that doesn't worked.
Do you have any Ideas how to get exact the same values in C# as in C++?

Translate C# code to VBNET

I need to translate this C# code from NReplayGain library here https://github.com/karamanolev/NReplayGain to a working VBNET code.
TrackGain trackGain = new TrackGain(44100, 16);
foreach (sampleSet in track) {
trackGain.AnalyzeSamples(leftSamples, rightSamples)
}
double gain = trackGain.GetGain();
double peak = trackGain.GetPeak();
I've translate this:
Dim trackGain As New TrackGain(samplerate, samplesize)
Dim gain As Double = trackGain.GetGain()
Dim peak As Double = trackGain.GetPeak()
Use an online converter. C# to VB converters:
dotnet Spider
SharpDevelop
teletrik.
developerFusion
Your c# code shown above has errors. Probably it is written in pseudo code. I have not found any declaration of a sample set at the github address you mentioned.
A semicolon is missing (inside the loop). The loop variable sampleSet is not declared. Where do leftSamples and rightSamples come from? The loop variable is not used inside the loop. Probably the left and right samples are part of the sampleSet. If I correct this, I can convert the code by using one of these online converters.
C#:
TrackGain trackGain = new TrackGain(44100, 16);
foreach (SampleSet sampleSet in track) {
trackGain.AnalyzeSamples(sampleSet.leftSamples, sampleSet.rightSamples);
}
double gain = trackGain.GetGain();
double peak = trackGain.GetPeak();
VB:
Dim trackGain As New TrackGain(44100, 16)
For Each sampleSet As SampleSet In track
trackGain.AnalyzeSamples(sampleSet.leftSamples, sampleSet.rightSamples)
Next
Dim gain As Double = trackGain.GetGain()
Dim peak As Double = trackGain.GetPeak()
After all, the two versions don't look that different!
It is fairly simple to reference within assemblies written in different languages.
I frequently reference C# code from F# and have referenced VB.NET code from C#.
Just be sure to compile both projects to target the same framework version, say .NET 4.5 or Mono 2.10 , and CPU architecture.
If you need the files to reside in the same assemblies. I would suggest you study the C# syntax and convert it manually.
Edit: After browsing the Repository, I only see a handful of classes.
Besides learning new languages is a great way to improve both your ability to write code and read code in the languages you are already comfortable with.
A good one online solution to translate .NET to C# and vice-versa, to another language, as JavaScript is CodeTranslator - Carlossag. Until now, I didn't have problems with this translator.

copying one Array value to another array

I have 2 array of object. 1st array of object have property which I want to copy to other array.
1st array of object
HotelRoomResponse[] hr=new HotelRoomResponse[100];
2nd array of object
RateInfos[] rt = new RateInfos[100];
now what i want to do is copy a property of 1st array like
rt=hr[].RateInfo;
but it give error. What is correct way to do this????
You can't just project an array like that. You effectively have to loop - although you don't need to do that manually in your own code. LINQ makes it very easy, for example:
RateInfos[] rt = hr.Select(x => x.RateInfo).ToArray();
Or you could use Array.ConvertAll:
RateInfos[] rt = Array.ConvertAll(hr, x => x.RateInfo);
In both of these cases there's still a loop somewhere - it's just not in your code.
If you're quite new to C# and don't understand LINQ, lambda expressions, delegates etc yet, then you could just write the code yourself:
RateInfos[] rt = new RateInfos[hr.Length];
for (int i = 0; i < rt.Length; i++)
{
rt[i] = hr[i].RateInfo;
}
All of these three will achieve the same result.
The first approach is probably the most idiomatic in modern C#. It will work with any input type, and you can change from ToArray() to ToList() to get a List<RateInfos> instead of an array, etc.
The second approach is slightly more efficient than the first and will work with .NET 2.0 (whereas LINQ was introduced in .NET 3.5) - you'll still need a C# 3 compiler or higher though. It will only work as written with arrays, but there's a similar ConvertAll method for List<T>.
The third approach is the most efficient, but obviously more code as well. It's simpler for a newcomer to understand, but doesn't express what you're trying to achieve as clearly when you know how all the language features work for the first two solutions.
RateInfos[] rt = hr.Select(item => item.RateInfo).ToArray();
Use LINQ:
RateInfos[] rt = hr.Select(x => x.RateInfo).ToArray();

Extract a vector from a two dimensional array efficiently in C#

I have a very large two dimensional array and I need to compute vector operations on this array. NTerms and NDocs are both very large integers.
var myMat = new double[NTerms, NDocs];
I need to to extract vector columns from this matrix. Currently, I'm using for loops.
col = 100;
for (int i = 0; i < NTerms; i++)
{
myVec[i] = myMat[i, col];
}
This operation is very slow. In Matlab I can extract the vector without the need for iteration, like so:
myVec = myMat[:,col];
Is there any way to do this in C#?
There are no such constructs in C# that will allow you to work with arrays as in Matlab. With the code you already have you can speed up process of vector creation using Task Parallel Library that was introduced in .NET Framework 4.0.
Parallel.For(0, NTerms, i => myVec[i] = myMat[i, col]);
If your CPU has more than one core then you will get some improvement in performance otherwise there will be no effect.
For more examples of how Task Parallel Library could be used with matrixes and arrays you can reffer to the MSDN article Matrix Decomposition.
But I doubt that C# is a good choice when it comes to some serious math calculations.
Some possible problems:
Could it be the way that elements are accessed for multi-dimensional arrays in C#. See this earlier article.
Another problem may be that you are accessing non-contiguous memory - so not much help from cache, and maybe you're even having to fetch from virtual memory (disk) if the array is very large.
What happens to your speed when you access a whole row at a time, instead of a column? If that's significantly faster, you can be 90% sure it's a contiguous-memory issue...

evaluate an arithmetic expression stored in a string (C#)

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string.
So like I got a string:
string myExpr="4*(80+(5/2))+2";
And I want to calculate the outcome of the arithmetic expression.
While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#.
I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so.
So... my question, Is there any 'simple' way to do this?
There's a javascript library you can reference, then just do something like:
var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);
Edit;
Library is Microsoft.JScript
You could just call the JScript.NET eval function. Any .NET language can call into any other.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.
I've used NCalc with great success. It's extremely flexible and allows for variables in your formulas. The formula you listed in your question could be evaluated this easily:
string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());
You need to implement an expression evaluator. It's fairly straightforward if you have the background, but it's not "simple". Eval in interpreted environments actually re-runs the language parser over the string; you need to emulate that operation, for the bits you care about, in your C# code.
Search for "expression evaluators" and "recursive descent parser" to get started.
If you have Bjarne Stroustrup's The C++ Programming Language, in Chapter 6 he explains step by step (in C++) how to do exactly what Chris Tavares suggests.
It's straightforward but a little heady if you're not familiar with the procedure.
I needed to do something similar for an undergrad projectand I found this
Reverse Polish Notation In C#
Tutorial and code to be extremely valuable.
It's pretty much just an implementation of converting the string to Reverse Polish Notation then evaluating it. It's extremely easy to use, understand and add new functions.
Source code is included.
Try something like this:
int mySum = 4*(80+(5/2))+2;
var myStringSum = mySum.toString();

Categories