Skip to content

Instantly share code, notes, and snippets.

@JonRurka
Last active January 23, 2018 20:30
Show Gist options
  • Save JonRurka/0298bda007a00332fb6f506a3704a22a to your computer and use it in GitHub Desktop.
Save JonRurka/0298bda007a00332fb6f506a3704a22a to your computer and use it in GitHub Desktop.
An arbitrary size matrix with addition, subtraction and multiplication.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
public class Matrix {
private float[,] data;
public int Rows { get; private set; }
public int Columns { get; private set; }
public float[,] Data { get { return data; } }
public Matrix(int rows, int columns)
{
Rows = rows;
Columns = columns;
data = new float[rows, columns];
}
public Matrix(float[,] newData)
{
Rows = newData.GetLength(0);
Columns = newData.GetLength(1);
data = newData;
}
public float this[int row, int column]
{
get
{
row = Mathf.Clamp(row, 0, Rows - 1);
column = Mathf.Clamp(column, 0, Columns - 1);
return data[row, column];
}
set
{
row = Mathf.Clamp(row, 0, Rows - 1);
column = Mathf.Clamp(column, 0, Columns - 1);
data[row, column] = value;
}
}
public void SetData(float[,] newData)
{
Rows = newData.GetLength(0);
Columns = newData.GetLength(1);
data = newData;
}
public override string ToString()
{
StringBuilder str = new StringBuilder();
for (int r = 0; r < Rows; r++)
{
for (int c = 0; c < Columns; c++)
{
str.AppendFormat("{0}, ", data[r, c]);
}
str.AppendLine();
}
return str.ToString();
}
public static Matrix operator +(Matrix lhs, Matrix rhs)
{
if (lhs.Rows != rhs.Rows || lhs.Columns != rhs.Columns)
throw new System.Exception("Rows and columns must match.");
Matrix result = new Matrix(lhs.Rows, lhs.Columns);
for (int r = 0; r < result.Rows; r++)
{
for (int c = 0; c < result.Columns; c++)
{
result[r, c] = lhs[r, c] + rhs[r, c];
}
}
return result;
}
public static Matrix operator -(Matrix lhs, Matrix rhs)
{
if (lhs.Rows != rhs.Rows || lhs.Columns != rhs.Columns)
throw new System.Exception("Rows and columns must match.");
Matrix result = new Matrix(lhs.Rows, lhs.Columns);
for (int r = 0; r < result.Rows; r++)
{
for (int c = 0; c < result.Columns; c++)
{
result[r, c] = lhs[r, c] - rhs[r, c];
}
}
return result;
}
// https://www.khanacademy.org/math/precalculus/precalc-matrices/multiplying-matrices-by-matrices/v/matrix-multiplication-intro
public static Matrix operator *(Matrix lhs, Matrix rhs)
{
if (lhs.Columns != rhs.Rows)
throw new System.Exception("left hand matrix colums must match right hand matrix rows.");
Matrix result = new Matrix(lhs.Rows, rhs.Columns);
for (int r = 0; r < result.Rows; r++)
{
for (int c = 0; c < result.Columns; c++)
{
// multiply
float sum = 0;
for (int rhr = 0; rhr < rhs.Rows; rhr++)
{
sum += lhs[r, rhr] * rhs[rhr, c];
}
result[r, c] = sum;
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment