How can I modify individual elements of a vector? - c#

I want to read from and write to individual elements of a VectorOfFloat. The problem is that there's no setter defined, which makes the brackets + index way of accessing the elements read only.
VectorOfFloat vector = new VectorOfFloat(5);
// vector[2] = 2.5F; // does not work
There's a workaround:
convert to array with ToArray()
modify array as desired
write array back with Clear() and Push()
float[] array = vector.ToArray();
array[2] = 2.5F;
vector.Clear();
vector.Push(array); // does work but is retarded
Console.WriteLine(vector[2]);
This seems to be very cumbersome just to write one element Is there a more direct approach to this?
Also, what is the missing setter worth if I can work around it?

The comments are correct. The way to gain access to the unmanaged array is trough the StartAddress property returning an IntPtr.
lock(vector)
{
var ptr_array=(float*)vector.StartAddress.ToPointer();
ptr_array[4]=1.0f;
}

Related

Modifying Array Length property through Reflection

So, I am stuck with one weird problem.
To give you idea what I want to achieve, but failed miserably:
int[] testArray = new int[100];
typeof(int[])
.GetProperty("Length", BindingFlags.Instance | BindingFlags.Public)
.SetValue(testArray, 50);
Yeah, that is, I want to modify C# arrays Length property (only make it less than actual size), without making new array and copying contents - to avoid GC etc etc...
Background:
In Unity, there is this function:
void SetIndices(int[] indices, MeshTopology topology, int submesh, bool calculateBounds);
As you see, SetIndices doesn't accept "start" and "end" or at least "length" as a parameter. This is why I want to modify Length of my indices array to trick this function.
Any ideas?
You can't resize an array in C#. That's the hard truth.
In fact, the Array.Resize method creates a new array and copies the values of the previous array in the new one.

In C#, Procedure that modifies incoming array by reversing it?

I've been trying to find a solution to this problem in particular.
Write a procedure that modifies the incoming array of ints by reversing it. Because this is a procedure, it will not return anything. Instead, I will have to modify the array directly, and because arrays are reference type variables, the array will be permanently changed even after this procedure. To reverse an array, imagine the array with an imaginary line in the middle of it, and then swap the numbers on the left with the numbers on the right side.
At the moment, this is the only code I've written down for the problem. Based on the code I've written so far, I don't think I'm approaching it towards the correct solution for it.
public void Test10(int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
}
You could use built-in Array.Reverse method, which reverses the sequence of the elements in the entire one-dimensional Array.
Array.Reverse(array); // reverse supplied array
Please note, System.Array.Reverse() does in place transformation.
There are 2 options based on your preference and need
int[] array = {1,3};
Array.Reverse(array);
This will reverse the original array
int[] array = {1,3};
var reversedArray = array.Reverse().ToArray();
This will use linq and new reversed array will be returned and original array will remain as it is

Start Index Of Multidimensional Array [duplicate]

Is it possible in c# to initialize an array in, for example, subindex 1?
I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.
As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.
But, I was wondering if it was possible to create a new non-zero based array
It is possible to do as you request see the code below.
// Construct an array containing ints that has a length of 10 and a lower bound of 1
Array lowerBoundArray = Array.CreateInstance(typeof(int), new int[1] { 10 }, new int[1] { 1 });
// insert 1 into position 1
lowerBoundArray.SetValue(1, 1);
//insert 2 into position 2
lowerBoundArray.SetValue(2, 2);
// IndexOutOfRangeException the lower bound of the array
// is 1 and we are attempting to write into 0
lowerBoundArray.SetValue(1, 0);
You can use Array.CreateInstance.
See Array Types in .NET
Not simply. But you can certainly write your own class. It would have an array as a private variable, and the user would think his array starts at 1, but really it starts at zero and you're subtracting 1 from all of his array accesses.
You can write your own array class
I don't think if it's possible to modify the starting index of arrays.
I would create my own array using generics and handle it inside.
Just keep of const int named 'offset' with a value of one, and always add that to your subscripts in your code.
I don't think you can create non-zero based arrays in C#, but you could easily write a wrapper class of your own around the built in data structures.This wrapper class would hold a private instance of the array type you required; overloading the [] indexing operator is not allowed, but you can add an indexer to a class to make it behave like an indexable array, see here. The index function you write could then add (or subtract) 1, to all index's passed in.
You could then use your object as follows, and it would behave correctly:
myArrayObject[1]; //would return the zeroth element.
In VB6 you could change the array to start with 0 or 1, so I think VBScript can do the same. For C#, it's not possible but you can simply add NULL value in the first [0] and start real value at [1]. Of course, this is a little dangerous...

How to fastly copy only a portion of an array to another array?

I'm writing a high-performance data structure. One problem I came across is there doesn't seem to be anyway to copy only a portion of an array to another array (preferably as quickly as possible). I also use generics, so I'm not really sure how I'd use Buffer.BlockCopy since it demands byte addresses and it appears to be impossible to objectively determine the size of an object. I know Buffer.BlockCopy works at a byte-level, but does it also count padding as a byte?
Example:
var tmo=new T[5];
var source = new T[10];
for(int i=5;i<source.Length;i++)
{
tmp[i-5]=source[i];
}
How would I do this in a faster way like Array.CopyTo?
You can use Array.Copy().
Array.Copy(source , 5, tmp, 0, tmp.Length);

Efficiently shrinking a two dimensional array in C#

What is an efficient way to shrink a two dimensional array to a smaller size in C#?
For example:
var bigArray = new object[100, 100];
var smallArray = new object[10, 10];
bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;
startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;
smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
How will you write SomeShrinkingMethod() ?
Thanks!
EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.
Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?
Yes the best method is almost certainly to loop over each cell, although it might be possible to copy a sequence of each 'row'. The method would need to know lower indices of the square to be copied from the source square, and the size (which might be implicit in the destination square definition).

Categories