是否可以简洁地将值从 a 提取List<T>
到M x 1 double[,] 数组中,从而减少代码行数?
我有一个类型定义为:
public class Trajectory
{
public Vector3 Position { get; set; }
// ... more codes
}
Vector3 定义为:
public struct Vector3
{
public float X;
public float Y;
public float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
// ... more vector3 operators
}
目前我有List<Trajectory> trajectory
。它最多有 80 个条目。我只想将每个条目的 X、Y、X 值存储trajectory
为240 x 1 double[,]
数组(按 X、Y、Z 值的顺序)。
我目前的解决方案相当冗长且丑陋。它是这样的:
// take a snapshot of current trajectory
List<Entry> tempEntry = new List<Entry> (Entries);
// create a temporary vector3Values
List<Vector3> vector3Values = new List<Vector3>();
foreach (Entry e in tempEntry)
{
vector3Values.Add(new Vector3(e.Position.X, e.Position.Y, e.Position.Z));
}
/* Start an index at 0.
* This is for foreach iteration to extract the value of x, y, and z from each vector3
*/
int index = 0;
// find the size of the list, in case max limit is changed
int listCount = inputVector3.Count;
/* set the length of the new array by multiplying the size of the list by 3.
* We want:
* [x1 x2 x3...xn y1 y2 y3...yn z1 z2 z3...zn]'.
* Therefore, the size of the reshaped array is three times of the original array *
*/
int maxRowLength = listCount * 3;
// create double[,] variable to store the reshaped data, three times the length of the actual list.
double[,] result = new double[maxRowLength, 1];
// start going for each vector, then store the x components in the double[,] array.
foreach (Vector3 vector3 in inputVector3)
{
result[index, 0] = vector3.X;
index++;
}
/* continuing from the previous index value, start going for each vector,
* then store the z components in the double[,] array.
*/
foreach (Vector3 vector3 in inputVector3)
{
result[index, 0] = vector3.Y;
index++;
}
/* continuing from the previous index value, start going for each vector,
* then store the z components in the double[,] array.
*/
foreach (Vector3 vector3 in inputVector3)
{
result[index, 0] = vector3.Z;
index++;
}
在一天结束时,我得到了我想要的。M x 1双 [,] 数组。我使用 double[,] 与我现在需要的 Matlab 的 MWArray 对象进行互操作。
所以,问题是,有没有一种简洁的方法来完成我在这里所做的事情?
已编辑:每秒需要多次进行此转换(感谢 Chris Sinclair 提出此问题),但是,目前这不是问题。