C#:创建class Matrix,计算矩阵点乘

1. 先在一个项目中(Test_02)添加一个类

2. 再将矩阵点乘的method复制进去(命名为Matrix.cs).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_02
{
    class Matrix
    {
        public static double[,] Dot_Product(double[,] A, double[,] B)
        {

            int m, p, n;

            m = A.GetLength(0);

            p = A.GetLength(1);

            if (p != B.GetLength(0)) return null;

            n = B.GetLength(1);

            double[,] C = new double[m, n];

            for (int i = 0; i < m; i++)
            {

                for (int j = 0; j < n; j++)
                {

                    double sum = 0;

                    for (int k = 0; k < p; k++)
                    {

                        sum = sum + A[i, k] * B[k, j];

                    }

                    C[i, j] = sum;

                }

            }

            return C;

        }
    }
}
 

3. 调用新添加的类.

切换到主程序界面:

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 System.IO;

namespace Test_02
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_701_Click(object sender, EventArgs e)
        {

                double[,] A = new double[3, 1] { { 1 }, { 2 }, { 3 } };
                double[,] B = new double[1, 3] { { 1, 2, 3 } };


                double[,] C = Matrix.Dot_Product(A, B);
                for (int i = 0; i < C.GetLength(0); i++)
                {
                    for (int j = 0; j < C.GetLength(1); j++)
                    {
                        richTextBox1.AppendText(C[i, j].ToString() + "\t");
                    }
                    richTextBox1.AppendText("\n");
                }
                richTextBox1.AppendText("\n\n");


                double[,] D = Matrix.Dot_Product(B, A);
                for (int i = 0; i < D.GetLength(0); i++)
                {
                    for (int j = 0; j < D.GetLength(1); j++)
                    {
                        richTextBox1.AppendText(D[i, j].ToString() + "\t");
                    }
                    richTextBox1.AppendText("\n");
                }
            }
        }
    }
}

  • 18
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值