我需要将两个不同的方阵统一为一个。
我们需要缓存一个非常大的距离矩阵。
我们使用的是按调用收费的地图提供商,因此我们需要进行许多小调用,然后将矩阵统一到一个矩阵中。对于没有计算的矩阵单元,我们可以插入一个非常大的数字,比如说inf
因此,让我详细说明一下(为了简单起见,我们假设我们有两个矩阵):
a b c d
a = a [0 5 2 6]
b [5 0 7 3]
c [2 7 0 9]
d [6 3 9 0]
e f g
b = e [0 5 8]
f [5 0 18]
g [8 18 0] 我需要创建以下矩阵
a b c d e f g
c = a [0 5 2 6 inf inf inf]
b [5 0 7 3 inf inf inf]
c [2 7 0 9 inf inf inf]
d [6 3 9 0 inf inf inf]
e [inf inf inf inf 0 5 8 ]
f [inf inf inf inf 5 0 18]
g [inf inf inf inf 8 18 0]有没有为统一这些矩阵而闻名的库,或者我应该从头开始构建它?
非常感谢!
发布于 2021-03-31 01:48:10
合并2个数组的最简单的内置选项是Concat
double[][] a = {
new double[] { -1, -2, -1, -2 },
new double[] { -5, -3, -4, -2 },
new double[] { -1, -2, -1, -2 },
new double[] { -5, -3, -4, -2 }
};
double[][] b = {
new double[] {1, 1, -1 },
new double[] { 3, 2, 3 },
new double[] { -5, -3, -4}
};
double[][] result = a.Concat(b).ToArray();
foreach (var line in result)
{
Console.WriteLine(string.Join(',', line));
}如果您有任何充分的理由在生成的矩阵中包含"inf“,则更有可能需要使用int.MaxValue之类的内容手动扩展初始数组
发布于 2021-04-02 19:31:48
我已经制作了一段代码,它可以实现我所要求的功能。通过在两个不同大小的矩阵的连接上添加较大的值来创建欧几里德方阵
Dictionary<string, Dictionary<string, double>> firstMatrix
= JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, double>>>(originalMatrixText);
Dictionary<string, Dictionary<string, double>> secondMatrix
= JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, double>>>(secondaryMatrixText);
//Create the dimension of the full matrix
List<string> totalPoints = new List<string>();
totalPoints.AddRange(firstMatrix.Keys);
totalPoints.AddRange(secondMatrix.Keys);
Dictionary<string, Dictionary<string, double>> finalMatrix = new Dictionary<string, Dictionary<string, doube>>();
foreach (string pointA in totalPoints)
{
string keyRow = pointA;
Dictionary<string, double> cells = new Dictionary<string, double>();
if (!finalMatrix.ContainsKey(keyRow))
{
foreach (string pointB in totalPoints)
{
string keyCell = pointB;
double distance = 0;
if (!cells.ContainsKey(keyCell))
{
if (firstMatrix.ContainsKey(keyRow) && firstMatrix.ContainsKey(keyCell))
{
//If the element was in the first matrix use this value
distance = firstMatrix[keyRow][keyCell];
}
else if (secondMatrix.ContainsKey(keyRow) && secondMatrix.ContainsKey(keyCell))
{
//If the element was in the second matrix use this value
distance = secondMatrix[keyRow][keyCell];
}
else
{
//If the element did not exist in either matrix use the max Value of Double
distance = double.MaxValue;
}
cells.Add(keyCell, distance);
}
}
finalMatrix.Add(keyRow, cells);
}
}https://stackoverflow.com/questions/66872186
复制相似问题