Question

To solve a problem I already asked here Best/Fastest Way To Change/Access Elements of a Matrix

I'm using single dimension arrays to store matrixes. But accessing elements of the matrix becomes a cumbersome task.

I'm currently storing my matrixes in arrays like this

type[numberOfRows * numberOfColumns] myArray;

And to access the [n][m] element I have to type this

blargh = myArray[(n*numberOfRows)+m];

... I'm wondering if its possible to overload / create new operators [][] that would 'translate' myArray[n][m] to myArray[(n*numberOfRows)+m]. And IF that IS possible, would that hinder the performance too much.

edit: turns out a 'forced-inline' method yields a performance gain.

    [MethodImpl(MethodImplOptions.AggressiveInlining)]public void set(int x, int y, T value)
    {
        array[(x * wid) + y] = value;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]public T get(int x, int y)
    {
        return array[(x*wid) + y];
    }
Was it helpful?

Solution

It is not possible to overload the operator for the array type, or change its definition; that can only be done from the definition of that type, which you can't control.

What you can do is create your own type that wraps the array, and that overloads the operators that you want:

public class Matrix<T>
{
    private T[] array;

    public T this[int row, int column]
    {
        get { return array[row + column]; }
    }
}

Whether or not the performance difference (which should be small, but not nothing) are an issue for your program is something that you're going to need to profile and measure.

OTHER TIPS

One way to implement double indexing (i.e. matrix[r][c] syntax) would be using a Proxy Pattern (also known as the Surrogate Pattern).

The idea is to overload the top-level operator[] to return a special object that "remembers" the first index and the array, and provides its own overload of the operator[] that combines the "remembered" first-level index with the supplied second-level index to produce the actual "flat" index into the data array.

In terms of the program logic, the proxy object represents the column of your matrix. Here is how you can implement this:

public class Matrix<T> {
    private readonly T[] data;
    private readonly int rowCount;
    public class Column {
        private readonly Matrix<T> m;
        private readonly int r;
        internal Column(Matrix<T> m, int r) {
            this.m = m;
            this.r = r;
        }
        public T this[int c] {
            get {
                return m.data[m.rowCount*r + c];
            }
        }
    }
    public Column this[int r] {
        get {
            return new Column(this, r);
        }
    }
}

The performance implications of this approach is that there would be an object created each time that you access the top level matrix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top