我正在尝试以易于检索和更新的格式将 3d 数组保存到文件中。我没有找到一种简单的方法来做到这一点。
它是一个 3 维的 int 数组。我更喜欢类似于这样的保存方法:
//save
for (int z1 = 0; z1 <= z; z1++)
{
for (int c = 0; c < m.Length; c++)
{
for (int x = 0; x < 4; x++)
{
writeToFile("matrix.txt", matrix[z1][c][x];
}
}
}
和类似的检索方法,但在这一点上我一点也不挑剔,任何能保存到文件并易于检索的东西都可以。
以上只是首选,因为它允许我仅保存保存数据的数组部分。
数组的大小类似于 m[4000][7000][4],但填充稀疏。
编辑:经过较长时间的运行后,我的机器无法运行这种大小的数组,因此我将切换到 xml 数据集。谢谢大家的建议,抱歉我无法更好地实现。
最佳答案
您需要的是工具。
现在这些是我的建议,还有其他解决方案,也许更适合......
首先去here并熟悉这个库。你需要的可能是this sparse matrix data structure或者可能是Sparse vector .
其次,如果你不关心文件保存的格式,那么.Net有一个奇妙的东西叫做二进制序列化explained here .
现在这一切听起来相当复杂,但大致如下: //这是在没有 VS 的情况下编写的...
// create a matrix, Im using a dense one, but you can use a sparse matrix in pretty much the same way
Matrix<double> matrix = DenseMatrix.OfArray(new double[,] {
{1,1,1,1},
{1,2,3,4},
{4,3,2,1}});
var formatter = new BinaryFormatter();
// saving
using(var fileStream1 = File.Create("file.file"))
{
formatter.Serialize(fileStream1, matrix);
}
Matrix<double> newMatrix= null;
// retreving
using(var fileStream2 = File.Open("file.file"))
{
newMatrix = (Matrix<double>)formatter.DeSerialize(fileStream2);
}
性能方面,这对于稀疏矩阵(该示例显示密集矩阵)应该非常有效,因为 Math.Net 使用 CSR所以保存他们的数据...
链接: http://numerics.mathdotnet.com/docs/ http://numerics.mathdotnet.com/api/MathNet.Numerics.LinearAlgebra.Single/SparseMatrix.htm http://numerics.mathdotnet.com/api/MathNet.Numerics.LinearAlgebra.Single/SparseVector.htm http://msdn.microsoft.com/en-us/library/72hyey7b%28v=vs.110%29.aspx http://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR_or_CRS.29
关于c# - 将 3d int 数组写入文件(并更新它)的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24303435/