0

I am trying to declare and use XNA Vectors for Matrix Multiplication, Summation, etc. in C#.

Those will be used for Image processing to make it faster than regular SetPixel and GetPixel. However, I am always failing to find a working example and I tried many examples online but it seems I am missing something.

Any help and sample code?

Thanks!

JoHa
  • 1,989
  • 10
  • 28
  • 42

2 Answers2

1

If you are worried about Performance then you can revert to coding in unsafe context.

By marking a type, type member, or statement block with the unsafe keyword, you're permitted to use pointer types and perform C++ style pointer operations on memory within that scope, and to be able to do this within the managed execution framework. Unsafe code can run faster than a corresponding safe implementation.

Here is a nice, short example that comes from the book C# 4.0 in a Nutshell:

unsafe void BlueFilter (int[,] bitmap)
  {
    int length = bitmap.Length;
    fixed (int* b=bitmap)
    {
        int* p=b;
        for (int i=0, i<length; i++)
        *p++ &= 0xFF;
    }
   }

(Source)


Apart from that you should also take a look at this SO Question

Why is matrix multiplication in .NET so slow?

Community
  • 1
  • 1
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
  • Thanks. But what about utilitizing the GPU? – JoHa Jul 05 '11 at 03:09
  • @johnshaddad | You cant directly Utilize GPU as their vendors don't provide a Managed API and nither they have x86/x64 based instruction sets, NVIDIA Provides CUDA but it only supports C++. So Though You can build an Interop Layer but using Parallelism Would be Lot Simpler :) – Shekhar_Pro Jul 05 '11 at 03:19
  • Oops lol but what about processing HD images in real-time? As in a video in HD that I would like to process live (eg. flipping the photo or doing anything else)? Any pointers to what works best for such cases, possibly with tutorial or sample code? Thanks – JoHa Jul 05 '11 at 03:26
0

Verctors are just 1 x n matrices. Create a Matrix class, with methods for summation and multiplication.

public class Matrix
{
    private int[,] m_array;

    public Matrix(int m, int n)
    {
        m_array = new int[m, n];
    }

    public Matrix(int[,] other)
    {
        m_array = other;
    }

    public Matrix Mult(Matrix other)
    {
        if (this.m_array.GetLength(1) != other.m_array.GetLength(0))
            return null;

        int[,] res = new int[this.m_array.GetLength(0), other.m_array.GetLength(1)];

        for (int i = 0; i < this.m_array.GetLength(0); ++i)
            for (int j = 0; j < other.m_array.GetLength(1); ++j)
            {
                int s = 0;
                for (int k = 0; k < this.m_array.GetLength(1); ++k)
                    s += this.m_array[i, k] * other.m_array[k, j];
                res[i, j] = s;
            }

        return new Matrix(res);
    }
}
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95