[英]C#: Declaring and Using XNA Vectors for Matrix Multiplication, et. al
I am trying to declare and use XNA Vectors for Matrix Multiplication, Summation, etc. in C#.我正在尝试在 C# 中声明和使用 XNA 向量进行矩阵乘法、求和等。
Those will be used for Image processing to make it faster than regular SetPixel and GetPixel.这些将用于图像处理,使其比常规的 SetPixel 和 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!谢谢!
If you are worried about Performance then you can revert to coding in unsafe
context.如果您担心性能,那么您可以在unsafe
的环境中恢复编码。
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 关键字标记类型、类型成员或语句块,您可以在 scope 内的 memory 上使用指针类型并执行 C++ 样式的指针操作,并且能够在框架内执行此操作。 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:这是一个很好的简短示例,来自 C# 4.0 一书简而言之:
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;
}
}
Apart from that you should also take a look at this SO Question除此之外,您还应该看看这个 SO Question
Why is matrix multiplication in .NET so slow? 为什么 .NET 中的矩阵乘法这么慢?
Verctors are just 1 xn matrices. Verctors 只是 1 xn 矩阵。 Create a Matrix class, with methods for summation and multiplication.创建一个矩阵 class,带有求和和乘法的方法。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.