converting type double[][] to float - c#

I have a function signature like:
static public double[][] G2Sweep(int row1, int row2, double[][] mtx)
{
mtx = (float) mtx;
}
But I need to covert the double[][] matrix into float values. How is this done as the code can't explicitly convert it?

public static float[][] Convert(double[][] mtx)
{
var floatMtx = new float[mtx.Length][];
for (int i = 0; i < mtx.Length; i++)
{
floatMtx[i] = new float[mtx[i].Length];
for (int j = 0; j < mtx[i].Length; j++)
floatMtx[i][j] = (float)mtx[i][j];
}
return floatMtx;
}
Or:
public static float[][] Convert(double[][] mtx)
{
return mtx.Select(i => i.Select(j => (float)j).ToArray()).ToArray();
}

No, you can't convert double to float in place, especially for arrays. You need to create copy with correct type.

Another way you can do this by is using the Array.ConvertAll method:
Array.ConvertAll<double, float>(doubles, d => (float)d);
Does the same looping and explicit converting, but looks better.

yes all values to float, but i'd prefer not having to do a for loop to lop through it all
Well, sorry, but you can't. Casting an array to a type like float (or int, or String, or MonkeyPoo, or whatever) makes no sense. If you need to look at every value in an array then you need a loop. There is no getting around that fact.
Lamdas and whatnot all boil down to a loop as well. You'll just need to bite the bullet and either A) Convert in a loop (or use something like .Cast<float>), or use the correct type to begin with.

It's true that you cant convert in place and that you have to loop through the values.
However, it's fair* to say nowadays that memory is cheap.
At the point of creating your double[][] variable; why not simply also create a float[][] at the same time, so the conversion is done one, in place.
that way in the rest of your lifecycle, you can just use the write array for the write task.
That said, can you clarify why you need a distinct float and double array ?
*Fair but not necessarily acceptable; if it's a webapp hosted on its own box or virtual image; then it's fine. If this is a standalone app that might have to work on a netbook or in Silverlight somewhere, it is not fair or fine.

You can avoid writing the loop by hand if you use Linq.
float[][] floats = mtx.Select(r=>r.Select(Convert.ToSingle).ToArray()).ToArray();
EDIT: fixed.

Related

How to map variable names to array indices

Say I have an array of fixed size N, is there a way to map the elements to a list of N variable names?
I was thinking of something like:
variable1, variable2, variable3 = arrayOfSize3;
EDIT:
A few people have remarked that this would be useless and suggested that I am doing something wrong. Maybe I am, but this is a pretty common feature in dynamic languages so I was hoping C# had something elegant as an alternative.
If it helps, I can write what I need it for. I have parsed an HTML table and have an array of strings representing a row of the table. I made a class to represent the row with variables representing the data, but to store the data I have to manually set the names to each of the array elements. I know there are other ways to do this, but I was wondering more out of curiosity than anything else, what is the right way to map variables like this?
Their is no such assignment, but you can do like this:
var variable1 = arrayOfSize3[0];
var variable2 = arrayOfSize3[1];
var variable3 = arrayOfSize3[2];
Not production ready yet, but you can do this in C# 7 preview which comes with Visual Studio 15 preview. Using deconstruction matching, the following code works with Tuple
var (variable1, variable2, variable3) = tupleOfSize3;
This feature actually works with anything with a deconstructor method like this
public void Deconstruct(out T1 x1, ..., out Tn xn) { ... }
Maybe array will have this extension. Please see What's new in C# 7.0
Tuples are a set of a fixed number values, each with its own name and type. Arrays, on the other hand, are a set of a variable number of anonymous values, all of the same type. These are two very distinct forms of aggregate types, and they really serve mostly disjoint use cases.
Having said that, it is possible to deconstruct an array (in C# 7 preview which comes with Visual Studio 15 preview)! You can do it by adding your own Deconstruct method as an extension method:
class C
{
public static void Main()
{
int[] x = new int[2];
var (a, b) = x;
}
}
static class ArrayUtilities
{
public static void Deconstruct(this int[] data, out int a, out int b)
{
a = data[0];
b = data[1];
}
}

How to convert String to One Int

following problem in C# (working in VS Community 2015):
First off, i fairly new to C#, so excuse me if that question would be an easy fix.
I have a contact sensor giving me a string of numbers (length measurement). I read them with the SystemPort Methods and cut them down to the numbers that i need with substring (as the beginning of the string, the "SR00002" is useless to me).
In the end i end up with a string like : "000.3422" or "012.2345". Now i want to convert that string to one solid int-variable that i can work with, meaning subtract values from and such.
Bsp: I want to calculate 012.234 - 000.3422 (or , instead of . but i could change that beforehand)
I already tried Parse and ConvertToInt (while iterating through the string) but the endresult is always a string.
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,");
string b2 = b1[1].Substring(1);
foreach (char c in b2)
{
Convert.ToInt32(c);
}
textBox2.Text = b2 + b2.GetType();
I know that when b2 will be int it can not be printed in the Textbox but ill take care of that later.
When everything is converted accordingly, ill outsource the conversion to its own method =)
The GetType is just for testing and as said shows only System.String (which i dont want). Help would be much appreaciated. I also browsed the searchfunction and google but couldnt find anything of help. I wish any possible helpers a nice day, mfg Chris.
use the int.Parse
int.Parse("123")
You need to assign the converted values to a new variable or array that takes int or other numeric values that you want.
int[] numbers = new int[b1.length];
for(int i = 0; i < b2.length; i++)
{
numbers[i] = Convert.ToInt32(b2[i]);
}

Is there a faster way to loop over an array in safe mode

I am writing a method to measure the frequency of a sampled sine wave. It takes a somewhat large 1D array (10^3 to 10^4 samples order of magnitude) and returns a double. A helper methods is also called within the body of the method that checks whether the wave is crossing zero. Here is an example of what I have written:
public static double Hertz(float[] v, int n) {
int nZCros = 0
for (int i = 1; i < n; i++) {
if (IsZeroCrossing(v.Skip(i - 1).ToArray())) {
++nZCros;
}
}
return (double)nZCros / 2.0;
}
private static bool IsZeroCrossing(float[] v) {
bool cross;
//checks if the first two elements of the array are opposite sign or not
return cross;
}
My problem is that method takes 200-300 ms to run. So I decided to try using unsafe and pointers, like this,
public unsafe static double Hertz(float* v, int n) {
int nZCros = 0
for (int i = 1; i < n; i++) {
if (IsZeroCrossing(&v[i - 1])) {
++nZCros;
}
}
return (double)nZCros / 2.0;
}
private unsafe static bool IsZeroCrossing(float* v) {
bool cross;
//checks if the first two elements of the array are opposite sign or not
return cross;
}
which runs in 2-4 ms.
However, I am not really comfortable with venturing outside the recommended bounds. Is there a way to achieve the same speed in a safe context? And if there isn't, does it defeat the purpose of using C#? Should I really be using C# for these kind of signal processing applications and scientific implementations?
This is just one of many DSP methods I'm writing which take a large array of samples as an input. But this one got me to realize there was a problem, because I accidentally put in 48000 samples instead of 4800 when I was testing this method and it took 20 seconds to return a value.
Thank you.
UPDATE: I tried adding Take(2) after Skip(i - 1) in the former snippet. This brought it down to 90-100 ms, but the question still stands.
You don't need to pass a copy of the array elements to IsZeroCrossing().
Instead, just pass the two elements you are interested in:
private static bool IsZeroCrossing(float elem1, float elem2)
{
return elem1*elem2 < 0.0f; // Quick way to check if signs differ.
}
And call it like so:
if (IsZeroCrossing(v[i-1], v[i]) {
It's possible that such a simple method will be inlined for a release build, making it as fast as possible.

Should I use Int32[,] or System.Drawing.Point when all I want is the x,y coordinates?

I am building an app that lets me control my Android devices from my PC. It's running great so now I want to start cleaning up my code for release. I'm trying to clean up solution references that I don't need so I took a look at the using System.Drawing; that I have for implementing the Point class. The thing is, I don't really need it if I switch to using a two-dimensional Int32 array.
So I could have: new Int32[,] {{200, 300}}; instead of new Point(200, 300); and get rid of the System.Drawing namespace altogether. The question is: does it really matter? Am I realistically introducing bloat in my app by keeping the System.Drawing namespace? Is Int32[,] meaningfully more lightweight?
Or, should I not use either and just keep track of the x,y coordinates in individual Int32 variables?
EDIT: I got rid of the original idea I wrote: Int32[200, 300] and replaced it with new Int32[,] {{200, 300}}; because as #Martin Mulder pointed out Int32[200, 300] "creates a two-dimensional array with 60000 integers, all of them are 0."
EDIT2: So I'm dumb. First of all I was trying to fancify too much by using the multi-dimensional array. Utter, overboard silliness. Secondly, I took the advice to use a struct and it all worked flawlessly, so thank you to the first four answers; every one of them was correct. But, after all that, I couldn't end up removing the System.Drawing reference because I was working on a WinForms app and the System.Drawing is being used all over in the designer of the app! I suppose I could further refactor it but I got the size down to 13KB so it's good enough. Thank you all!
Just create your own:
public struct Point : IEquatable<Point>
{
private int _x;
private int _y;
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
public Point(int x, int y)
{
_x = x;
_y = y;
}
public bool Equals(Point other)
{
return X == other.X && Y == other.Y;
}
public override bool Equals(object other)
{
return other is Point && Equals((Point)other);
}
public int GetHashCode()
{
return unchecked(X * 1021 + Y);
}
}
Better yet, make it immutable (make the fields readonly and remove the setters), though if you'd depended on the mutability of the two options you consider in your question then that'll require more of a change to how you do things. But really, immutability is the way to go here.
You are suggesting very ill advised:.
new Point(200, 300) creates a new point with two integers: The X and Y property with values 200 and 300.
new Int32[200,300] creates a two-dimensional array with 60000 integers, all of them are 0.
(After your edit) new Int32[,] {{200, 300}} also creates a two-dimensional array, this time with 2 integers. To retrieve the first value (200), you can access it like this: array[0,0] and the second value (300) like array[0,1]. The second dimension is not required or needed or desired.
If you want to get rid of the reference to the library there are a few other suggestions:
new Int32[] {200, 300} creates an one-dimensional array of two integers with values 200 and 300. You can access them with array[0] and array[1].
As Ron Beyer suggested, you could use Tuple<int, int>.
Create your own Point-struct (pointed out by Jon Hanna). It makes your applicatie a bit larger, but you prevent the reference and you prevent the library System.Drawing is loaded into memory.
If I wanted to remove that reference, I would go for the last option since it is more clear to what I am doing (a Point is more readable than an Int32-array or Tuple). Solution 2 and 3 are slightly faster that solution 1.
Nothing gets "embedded" in your application by just referencing a library. However, if the Point class really is all you need, you could just remove the reference and implement you own Point struct. That may be more intuitive to read instead of an int array.
Int32[,] is something different by the way. It's a two-dimensional array, not a pair of two int values. You'll be making things worse by using that.
You could use Tuple<int, int>, but I'd go for creating your own structure.
As some people have suggested implementations here. So just wrap your two integers, I'd just use this:
public class MyPoint
{
public int X;
public int Y;
}
Add all other features only if needed.
As #Glorin Oakenfoot said, you should implement your own Point class. Here's an example:
public class MyPoint // Give it a unique name to avoid collisions
{
public int X { get; set; }
public int Y { get; set; }
public MyPoint() {} // Default constructor allows you to use object initialization.
public MyPoint(int x, int y) { X = x, Y = y }
}

Best way to use Math.NET statistics functions on the properties of objects in a List

I'm trying to figure out the best way to perform a computation fast and wanted to find out what sort of approach people would usually take in a situation like this.
I have a List of objects which have properties that I want to compute the mean and standard deviation of. I thought using this Math.NET library would probably be easier/optimised for performance.
Unfortunately, the input arguments for these functions are arrays. Is my only solution to write my own function to compute means and STDs? Could I write some sort of extension method for lists that uses lambda functions like here? Or am I better off writing functions that return arrays of my object properties and use these with Math.NET.
Presumably the answer depends on some things like the size of the list? Let's say for argument's sake that the list has 50 elements. My concern is purely performance.
ArrayStatistics indeed expects arrays as it is optimized for this special case (that's why it is called ArrayStatistics). Similarly, StreamingStatistics is optimized for IEnumerable sequence streaming without keeping data in memory. The general class that works with all kind of input is the Statistics class.
Have you verified that simply using LINQ and StreamingStatistics is not fast enough in your use case? Computing these statistics for a list of merely 50 entries is barely measurable at all, unless say you do that a million times in a loop.
Example with Math.NET Numerics v3.0.0-alpha7, using Tuples in a list to emulate your custom types:
using MathNet.Numerics.Statistics;
var data = new List<Tuple<string, double>>
{
Tuple.Create("A", 1.0),
Tuple.Create("B", 2.0),
Tuple.Create("C", 1.5)
};
// using the normal extension methods within `Statistics`
var stdDev1 = data.Select(x => x.Item2).StandardDeviation();
var mean1 = data.Select(x => x.Item2).Mean();
// single pass variant (unfortunately there's no single pass MeanStdDev yet):
var meanVar2 = data.Select(x => x.Item2).MeanVariance();
var mean2 = meanVar2.Item1;
var stdDev2 = Math.Sqrt(meanVar2.Item2);
// directly using the `StreamingStatistics` class:
StreamingStatistics.MeanVariance(data.Select(x => x.Item2));
The eaisiest solution you can use is to put Linq so that transform List to array
List<SomeClass> list = ...
GetMeanAndStdError(list.ToArray()); // <- Not that good performance
However, if perforamance is your concern, you'd rather compute Mean and Variance explicitly (write your own function):
List<SomeClass> list = ...
Double sumX = 0.0;
Double sumXX = 0.0;
foreach (var item in list) {
Double x = item.SomeProperty;
sumX += x;
sumXX += x * x;
}
Double mean = sumX / list.Count;
Double variance = (sumXX / list.Count - mean);

Categories