Skip to content

Instantly share code, notes, and snippets.

@KristofferK
Created January 25, 2018 20:12
Show Gist options
  • Save KristofferK/11240eaefbc92782078b81ffc6b6303c to your computer and use it in GitHub Desktop.
Save KristofferK/11240eaefbc92782078b81ffc6b6303c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatrixMultiplying
{
class Program
{
static void Main(string[] args)
{
Matrix m1 = new Matrix(new int[,]
{
{ 1, 2, 3 },
{ 4, 5, 6 }
});
Matrix m2 = new Matrix(new int[,]
{
{ 6, 5 },
{ 4, 3 },
{ 2, 1 },
});
Matrix m3 = new Matrix(new int[,]
{
{ 1, 2, 3 }
});
Matrix m4 = new Matrix(new int[,]
{
{ 13, 9, 7, 15 },
{ 8, 7, 4, 6 },
{ 6, 4, 0, 3 },
});
Console.WriteLine(m1);
Console.WriteLine(m2);
var m1m2 = m1.Times(m2);
var m2m1 = m2.Times(m1);
var m3m4 = m3.Times(m4);
Console.WriteLine(m1m2);
Console.WriteLine(m2m1);
Console.WriteLine(m3m4);
}
}
class Matrix
{
private int[,] nums;
public Matrix(int[,] nums)
{
this.nums = nums;
}
public Matrix Times(Matrix other)
{
var result = new int[nums.GetLength(0), other.nums.GetLength(1)];
for (int y = 0; y < nums.GetLength(0); y++)
{
for (int x = 0; x < other.nums.GetLength(1); x++)
{
for (int i = 0; i < nums.GetLength(1); i++)
{
result[y, x] += nums[y, i] * other.nums[i, x];
}
}
}
return new Matrix(result);
}
public override string ToString()
{
var sb = new StringBuilder();
for (var i = 0; i < nums.GetLength(0); i++)
{
for (var j = 0; j < nums.GetLength(1); j++)
{
sb.Append(nums[i, j] + " ");
}
sb.Append("\n");
}
return string.Join("\n", sb.ToString().Split('\n').Select(e => e.Trim()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment