首页 > 解决方案 > 矩阵乘法:向量到矩阵的转换

问题描述

我刚开始学习 Math.NET Numerics,发现它对矩阵乘法有用且功能强大。现在对我来说非常具有挑战性,因为我刚刚开始学习 C#,我希望我能在这里找到一些解决方案来帮助我完成整个旅程。先感谢您!

目标:

  1. 从 Excel 文件中提取填充在第一列和第二列中的数据并将它们放入 nx2 矩阵中(其中 n 可以是任意数量的行,这里我设置为 3000,所以它是 3000x2 矩阵)

  2. 从矩阵的第一列中提取数据乘以 5 并存储在向量 1 (VColumn) 中。同样,从矩阵的第二列中提取数据乘以 2 并存储在向量 2 (VRow) 中。使用这种方法,我可以将每一列与不同的值相乘。(有没有其他更直接的方法可以使用 .Multiply 关键字以矩阵形式单独乘以每个列值?)从我从输出中看到的,它显示在一行而不是一列中。

显示在一行而不是一列

  1. 将向量 1 和向量 2 放入矩阵形式(3000x2 矩阵格式)。但我得到的输出是 0。虽然不确定这是正确的方法......我如何为这部分或任何其他替代方案编码?

输出零

我不确定这是否是编码矩阵乘法的正确方法。如果有其他方法,请分享,因为我还在学习。非常感谢!

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());
        }
    }
}

标签: c#winformsvectormatrix-multiplicationmath.net

解决方案


使用线性代数,您可以使用矩阵*矩阵乘法获得相同的结果

图片

使用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
    // ...

}

推荐阅读