在進行空間統計實驗過程中,經常涉及到空間權重矩陣的處理,有時候需要將ArcGIS生成的swm格式的權重矩陣轉換為形如“0 1”的方陣格式。這里將我的辦法整理出來。
1.用如下工具箱生成swm格式的權重矩陣
2.將swm格式的權重矩陣轉換為dbf屬性表
3.用excel打開dbf將其轉換為txt文本文件
4.寫程序轉換格式並保存
代碼如下:
1 static void Main(string[] args) 2 { 3 //讀取文件並轉換格式 4 StreamReader sr = File.OpenText("E:\\AcaDissertation\\Data\\weight_arc.txt"); 5 double[,] weights = new double[47, 47]; 6 while (sr.ReadLine() != null) 7 { 8 string[] line = sr.ReadLine().Split('\t'); 9 10 weights[int.Parse(line[0])-1, int.Parse(line[1])-1] = double.Parse(line[2]); 11 } 12 SaveMatrix(weights, "E:\\AcaDissertation\\Data\\weight_mat.txt"); 13 Console.WriteLine("好了!"); 14 } 15 16 // 保存矩陣到文件 17 public static void SaveMatrix(double[,] InMatrix, string OutFileName) 18 { 19 int row = InMatrix.GetLength(0), col = InMatrix.GetLength(1); 20 FileStream aFile = new FileStream(OutFileName, FileMode.OpenOrCreate); 21 StreamWriter sw = new StreamWriter(aFile); 22 for (int i = 0; i < row; i++) 23 { 24 for (int j = 0; j < col; j++) 25 { 26 sw.Write("{0}{1}", InMatrix[i, j], " "); 27 } 28 sw.WriteLine(); 29 } 30 sw.Close(); 31 }
最后的最后,轉換后的權重矩陣為: