我刚刚开始学习Math.NET数值,并发现它对于矩阵乘法目的有用且功能强大。现在,由于我刚开始学习C#,这对我来说是很大的挑战,我希望能在这里找到一些解决方案来帮助我。预先谢谢你!
目标:
从填充在第一列和第二列中的Excel文件中提取数据,并将其放入nx2矩阵(其中n可以是任意行数,这里我设置为3000,所以它是3000x2矩阵)
从Matrix的第一列中提取数据以乘以5,然后存储在向量1(VColumn)中。类似地,从矩阵的第二列中提取数据以乘以2并存储在向量2(VRow)中。使用这种方法,我可以将每个列乘以不同的值。 (是否还有其他更直接的方法使用.Multiply关键字以Matrix形式分别乘以每个列值?)从输出中看到的是,它显示在一行中而不是一行中。
我不确定这是否是矩阵乘法编码的正确方法。如果还有其他方法,请在我还在学习的同时分享。非常感谢!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.Data.Text;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Matrix<Double> fileMatrix = DelimitedReader.Read<Double>
(@"C:\Users\Student\Downloads\MatricesData.xls", false, "\t", true); //Objective 1
textBox1.AppendText(fileMatrix.ToString());
Vector<Double> x = Vector<Double>.Build.Dense(3000, 1); //Objective 2
Vector<Double> y = Vector<Double>.Build.Dense(3000, 1);
Vector<Double> VColumn = fileMatrix.Column(0);
Vector<Double> VRow = fileMatrix.Column(1);
VColumn.Multiply(5.0, x);
VRow.Multiply(1.0, y);
textBox1.AppendText(x.ToString());
textBox1.AppendText(y.ToString());
Matrix<Double> z = Matrix<Double>.Build.Dense(3000, 2); //Objective 3: Need help
z.InsertColumn(0, VColumn);
z.InsertColumn(1, VRow);
textBox1.AppendText(z.ToString());
}
}
}
答案 0 :(得分:1)
使用线性代数,您可以通过矩阵*矩阵乘法获得相同的结果
使用MathNet
以上是
static void Main(string[] args)
{
var fileMatrix = DelimitedReader.Read<double>("data.csv",
sparse: false,
delimiter: "\t",
hasHeaders: true
);
// 5.2 1.8
// 3.2 0.2
// 1.8 2.8
// 4.4 3.4
// 5.2 0.6
// ...
var coefMatrix = CreateMatrix.DiagonalOfDiagonalArray(new double[] { 5, 2 });
var resultMatrix = fileMatrix * coefMatrix;
// 26 3.6
// 16 0.4
// 9 5.6
// 22 6.8
// 26 1.2
// 16 2.8
// ...
}
答案 1 :(得分:0)
InsertColumn创建一个新矩阵并插入一列:
矩阵InsertColumn(int columnIndex,Vector column) 创建一个新矩阵并将给定列插入给定索引。
您需要某个版本的SetColumn:
void SetColumn(int columnIndex,Vector column) 要么 void SetColumn(int columnIndex,int rowIndex,int length,Vector column) 要么 void SetColumn(int columnIndex,Double []列)