This project has moved and is read-only. For the latest updates, please go here.

SubMatrix copy

Mar 20, 2015 at 6:12 PM
I have a matrix and I want to swap quandrant 1 with quandrant 3 and quandrant 2 with quadrant 4. For example

1 2 3
4 5 6
7 8 9


9 7 8
3 1 2
6 4 5

I can do this with the MathNet SubMatrix method as shown below. I will typically be doing this on matrices the size of 1000 x 1000. Is this the most efficient way? Is there a way to do this with BlockCopy?
public static double[,] MatrixShift(double [,] a)
    var matA = DenseMatrix.OfArray(a);

    var N = a.GetLength(0);
    var M = a.GetLength(1);
    var n = (int)Math.Ceiling(N / 2.0);
    var m = (int)Math.Ceiling(M / 2.0);

    var A11 = matA.SubMatrix(0, n, 0, m);
    var A12 = matA.SubMatrix(0, n, m, M - m);
    var A21 = matA.SubMatrix(n, N - n, 0, m);
    var A22 = matA.SubMatrix(n, N-n, m, M-m);

    var B = new DenseMatrix(N,M);

    B.SetSubMatrix(0, 0, A22);
    B.SetSubMatrix(0, M - m, A21);
    B.SetSubMatrix(N-n, 0, A12);
    B.SetSubMatrix(N-n, M-m, A11);

    return B.ToArray();
Mar 22, 2015 at 7:00 PM
The matrix storage can also copy directly from one sub-matrix to another sub-matrix (Storage.CopySubMatrixTo), so you could copy directly from A to B without extracting the 4 matrices.

It actually does use BlockCopy internally if applicable, although this does not help that much in case of sub-matrices. However, in this case you'll loose a lot already by the conversion from 2D arrays to matrices and back to 2D arrays, since dense matrices use a single (1D) column-major array internally. I assume the 2D arrays are a requirement in your scenario?
Marked as answer by cdrnet on 4/10/2015 at 10:58 PM
Mar 23, 2015 at 3:27 PM
I would prefer to keep it in a 2D array but maybe I should rethink this. I was not aware that DenseMatrix.OfArray(a) creates a new copy of the data and stores it in a different format.

BTW, are ther any plans to add 2D FFT support?

Mar 23, 2015 at 8:54 PM
No concrete plans. But FFT is high on the list to work on, mainly to bring in native provider support.