Fastest way to zero out a 2D array in C# - c#

I have a 2D array that I want to clear and reset to 0 values. I know how to clear a vector (1D array) using Array.Clear() but I don't know the best way to clear a 2D matrix.
double D = new double[10];
Array.Clear(D, 0, D.Length);
How does one clear a 2D N x M array
double D[,] = new double[N,M];
Thank you for any help you may be able to provide.

Array.Clear works with multidimensional arrays, too:
double[,] D = new double[M,N];
Array.Clear(D, 0, D.Length);
Note, there's no need to compute the length yourself, since the Length property returns the total number of elements, regardless of the number of dimensions:
A 32-bit integer that represents the total number of elements in all the dimensions of the Array; zero if there are no elements in the array.

You can use the same method, but you may have to calculate your real length parameter value:
double D[,] = new double[N,M];
Array.Clear(D, 0, M*N);
I would use M*N because it's more readable, and I don't know what Length property returns for 2-dimmentional array.

Just reallocate it.
double D[,] = new double[N,M];
creates a empty 2D array.

Related

Finding All Combinations of a Multidimention Array with a Max Value in C#

Let's say I have an int[8,6] array which can have the maximum value of 255 per cell and I want to find all combinations of this array.
What is the most efficient way to accomplish this?
For array size N (1D array for simpliciry, 2D case works similar) and maximum value M there are M^N possible combinations. Every combination corresponds to value in range 0..M^N-1, so we can just walk throug this range and get combination for every value. Of course, it is possible for reasonable small values of N and M.
Python-like pseudocode:
int A[N]
P = M**N #math.intpower(M, N)
for i in range(P):
t = i
for k in range(N): #number of cells, number of digits in counter value
A[k] = t % M # value in k-th cells of result for variant number i
t = t // M #integer division
Note that for base M=256 you perhaps don't need to use division - needed values are just bytes of multibyte representation of big number in base 256

What's the fastest way to convert a float[] to byte[]?

OpenCV uses floats to store SIFT descriptors, where actually it is integer values from 0 to 255.
I am using OpenCvSharp, which is a C# wrapper for OpenCV and I would like to convert the float-based descriptors to byte[] because it takes only 1/4 of the space.
Before I realized that, I was converting the float[] to byte[] like this to store the descriptors in a database:
float[] floatDescriptor = ...;
byte[] byteDescriptor = new byte[floatDescriptor.Length * sizeof(float)];
Buffer.BlockCopy(floatDescriptor, 0, byteDescriptor, 0, byteDescriptor.Length);
This was very fast, because I could copy the whole float array without any transformation into a byte array. But it takes 4 times more space than this:
float[] floatDescriptor = ...;
byte[] byteDescriptor = new byte[floatDescriptor.Length];
for (int i = 0; i < floatDescriptor.Length; ++i)
{
byteDescriptor [i] = (byte)floatDescriptor[i];
}
But this is a lot slower. Is there a faster way to do it?
Edit
I am aware of the fact, that two different things are happening there. I'm just wondering if there is some kind of faster way for batch processing casts in arrays. Like Buffer.BlockCopy() is faster than BitConverter.GetBytes(float) for every float in an array.

Role of subscript operator in arrays

We declare multi-dimension array in C# as
Datatype[,] <arrayname> = new Datatype[size,size];
I was just wondering what's the role of subscript operator[,] here. Can someone explain above syntax how it works exactly?
Datatype[,] identifier;
delclares a two-dimensional array of Datatype. The general syntax is, for n dimensions you put n - 1 commas (,) between the square brackets. For example for a four-dimensional array, put three commas:
Datatype[,,,] identifier;
When you instantiate the array you have to set the size of each dimension, e.g.:
int sizeDimOne = 5, sizeDimTwo = 10, sizeDimThree = 10;
Datatype[,,] identifier = new Datatype[sizeDimOne, sizeDimTwo, sizeDimThree];
As part of a declaration, this part:
[,]
means "2-dimensional array", a rectangular array that will have 2 dimensions. You can call them "width" and "height" or whatever you wish, but 2 there is.
The number of commas denote the number of dimensions, minus 1, meaning that to declare a 3-dimensional array you would use 2 commas:
Datatype[,,] = ...
Object initialization in C# occurs in two step:
1)Create reference to the required type i.e int []num
2)Allocating physical memory of that object type i.e new num[2]
The subscript operator on the left-hand side gives an indication to the CLR that object that is currently being allocated to memory is fully compatible with the type of physical object that is being allocated memory.
For multidimensional array, each comma adds a dimension to array
For 1-D array []
2-D Array [,]
3-D Array[,,]

c# Buffer explanation

This might be a really beginer's question but I've been reading about this and I'm finding it hard to understand.
This is a sample from the msdn page about this subject (just a little smaller).
using System;
class SetByteDemo
{
// Display the array contents in hexadecimal.
public static void DisplayArray(Array arr, string name)
{
// Get the array element width; format the formatting string.
int elemWidth = Buffer.ByteLength(arr) / arr.Length;
string format = String.Format(" {{0:X{0}}}", 2 * elemWidth);
// Display the array elements from right to left.
Console.Write("{0,7}:", name);
for (int loopX = arr.Length - 1; loopX >= 0; loopX--)
Console.Write(format, arr.GetValue(loopX));
Console.WriteLine();
}
public static void Main()
{
// These are the arrays to be modified with SetByte.
short[] shorts = new short[2];
Console.WriteLine("Initial values of arrays:\n");
// Display the initial values of the arrays.
DisplayArray(shorts, "shorts");
// Copy two regions of source array to destination array,
// and two overlapped copies from source to source.
Console.WriteLine("\n" +
" Array values after setting byte 1 = 1 and byte 3 = 200\n");
Buffer.SetByte(shorts, 1, 1);
Buffer.SetByte(shorts, 3, 10);
// Display the arrays again.
DisplayArray(shorts, "shorts");
Console.ReadKey();
}
}
SetByte should be easy to understand, but if I print the shorts array before doing the SetByte operation the array looks like this
{short[2]}
[0]: 0
[1]: 0
After doing the first Buffer.SetByte(shorts, 1, 1); the array becomes
{short[2]}
[0]: 256
[1]: 0
And after setting Buffer.SetByte(shorts, 3, 10); the array becomes
{short[2]}
[0]: 256
[1]: 2560
At the end, in the example they print the array from right to left:
0A00 0100
I don't understand how this works, can someone give me to some information about this?
The Buffer class allows you to manipulate memory as if you were using a void pointer in c, it's like a sum of memcpy, memset, and so on to manipulate in a fast way memory on .net .
When you passed the "shorts" array, the Buffer class "sees" it as a pointer to four consecutive bytes (two shorts, each of them two bytes) :
|[0][1]|[2][3]|
short short
So the uninitialized array looks like this:
|[0][0]|[0][0]|
short short
When you do Buffer.SetByte(shorts, 1, 1); you instruct the Buffer class to change the second byte on the byte array, so it will be:
|[0][1]|[0][0]|
short short
If you convert the two bytes (0x00, 0x01) to a short it is 0x0100 (note as these are the two bytes one after other, but in reverse order, that's because the C# compiler uses little endianness), or 256
The second line basically does the same Buffer.SetByte(shorts, 3, 10);changes third byte to 10:
|[0][1]|[0][10]|
short short
And then 0x00,0x0A as a short is 0x0A00 or 2560.
The .NET types use little endianness. That means that the first byte (0th, actually) of a short, int, etc. contains the least significant bits.
After setting the array it seems like this as byte[]:
0, 1, 0, 10
As short[] it is interpreted like this:
0 + 1*256 = 256, 0 + 10*256 = 2560
i think the part that people might struggle with is that the Buffer.SetByte() method is basically iterating over the array differently than a regular assignment with the array indexer [], which would separate the array according to the width of the containing type(shorts/doubles/etc.) instead of bytes... to use your example:
the short array is usually seen as
arr = [xxxx, yyyy](in base 16)
but the SetByte method "sees" it as:
arr = [xx, yy, zz, ww]
so a call like Buffer.SetByte(arr, 1, 5) would address the second byte in the arry, which is still inside the first short. setting the value there and that's it.
the result should look like:
[05 00, 00 00] in hex or [1280,0].

What is the difference between Array.GetLength() and Array.Length?

How do you use the Array.GetLength function in C#?
What is the difference between the Length property and the GetLength function?
GetLength takes an integer that specifies the dimension of the array that you're querying and returns its length. Length property returns the total number of items in an array:
int[,,] a = new int[10,11,12];
Console.WriteLine(a.Length); // 1320
Console.WriteLine(a.GetLength(0)); // 10
Console.WriteLine(a.GetLength(1)); // 11
Console.WriteLine(a.GetLength(2)); // 12
For 1-dimensional arrays Length and GetLength(0) are exactly the same.
For arrays of higher rank Length is the product of all GetLength(0..Rank-1) values, in other words it is always the total number of fields.
The .Length property returns the number of elements in an array, whether it be one dimensional or multidimensional. That is a 2x6 array will have length of 12.
The .GetLength(0) method returns number of elements in the row direction in a multidimensional array. For a 2x6 array that is 2.
The .GetLength(1) method returns number of elements in the column direction in a multidimensional array. For a 2x6 array that is 6.
These do not return an actual element value, as stated by the chosen answer above.
GetLength returns the length of a specified dimension of a mulit-dimensional array.
Length returns the sum of the total number of elements in all the dimensions.
For a single-dimensional array, Length == GetLength(0)
For a two-dimensional array, Length == GetLength(0) * GetLength(1)
etc.
In mathematical term, we call as m rows and n columns, so the results is product of m*n for a two dimensional array. In this case GetLength(0) = m rows and GetLength(1)= n columns. For e.g see below example
string[,] stocks ={{"RELIND","Reliance Industries","1006.30"},{"TATMOB","Tata Mobiles","504.10"},{"ALST","Allstate","800.00"}, {"GE","GE Motors","810.00"}
};
The stocks arrays return GetLength(0)= 4 and GetLength(1)=3 and length =12

Categories

Resources