如何ILArray转换为双[,]数组? [英] How to convert ILArray into double[,] array?
问题描述
如何转换成ILArray双[,]数组
How convert ILArray into double[,] array
我 ILArray<双> A
要使用 A.ToArray()
,但不知道如何使用它
I have ILArray<double> A
want to use A.ToArray()
, but don't know how to use it
我需要获得双击[,]的System.Array
。
推荐答案
有是用于转换 ILArray<没有天然的支持;双>
成一个多维的System.Array双[,]
在当前ILNumerics。因此,让我们写吧!
There is no natural support for converting an ILArray<double>
into an multi dimensional System.Array double[,]
in ILNumerics currently. So let's write it!
private static System.Array ToSystemMatrix<T>(ILInArray<T> A) {
using (ILScope.Enter(A)) {
// some error checking (to be improved...)
if (object.Equals(A, null)) throw new ArgumentException("A may not be null");
if (!A.IsMatrix) throw new ArgumentException("Matrix expected");
// create return array
System.Array ret = Array.CreateInstance(typeof(T), A.S.ToIntArray().Reverse().ToArray());
// fetch underlying system array
T[] workArr = A.GetArrayForRead();
// copy memory block
Buffer.BlockCopy(workArr, 0, ret, 0, Marshal.SizeOf(typeof(T)) * A.S.NumberOfElements);
return ret;
}
}
此功能应该在任意 ILArray< T>任意元素类型和任意大小/尺寸
。 (然而,一如既往,你应该做的才去生产大量的测试!)它创建所需的尺寸和类型,副本自然(存储布局)顺序排列的所有元素的新的System.Array。该System.Array的返回可以投给真正的多维数组之后。
This function should work on arbitrary ILArray<T>
of arbitrary element type and arbitrary sizes / dimensions. (However, as always, you should do extensive testing before going productive!) It creates a new System.Array of the desired size and type and copies all elements in their natural (storage layout) order. The System.Array returned can get cast to the true multidimensional array afterwards.
我们使用 Buffer.BlockCopy
,以复制的元素。请记住,System.Array的存储它以行优先顺序的元素。 ILNumerics(就像FORTRAN,MATLAB和其他人)喜欢柱大订单!所以,既然我们只是快速复制的元素,做任何努力,重新排序在内存中,outcoming阵列将显示为具有比较翻到输入数组的尺寸:
We use Buffer.BlockCopy
in order to copy the elements. Keep in mind, System.Array stores its elements in row major order. ILNumerics (just like FORTRAN, Matlab and others) prefers column major order! So, since we just copy the elements quickly and do no efforts to reorder them in memory, the outcoming array will appear as having the dimensions flipped in comparison to the input array:
ILArray<double> C = ILMath.counter(4, 3);
var exp = ToSystemMatrix<double>(C);
EXP
将大小[3× 4。对于矩阵,这可以很容易地通过转输入数组规避:
exp
will be of size [3 x 4]. For matrices, this can easily be circumvented by transposing the input array:
var exp = ToSystemMatrix<double>(C.T);
@Edit:修正:使用Marshal.Sizeof(T),而不是的sizeof(双)
@Edit:修正:现在固定修复:使用Marshal.Sizeof(typeof运算(T))
@ bugfix: used Marshal.Sizeof(T) instead of sizeof(double) @ bugfix: now fixed the fix: used Marshal.Sizeof(typeof(T))
这篇关于如何ILArray转换为双[,]数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!