Creating a matrix class in Java Part 1

When I was reading G. Strang's "Linear Algebra and Its Applications" and looking for an API in Java, I found a page called "Let's make a matrix class". Previously I created a rudimentary complex class. I haven't written it in the article. I also wanted to put together my own math library someday, so I created a class that reflects the property of complex numbers, which is -1 when squared. To put it nicely, it feels like I made my own data structure around that and the algorithm that becomes -1 when squared. A self-made complex class object receives two integers, and the latter integer is treated as a coefficient of complex i. In other words, when we receive the array [1,3], we have created a class that mathematically interprets it as 1 + 3i. It's the sum of 1 as a real number and i × 3 imaginary. I also created a method (algorithm) for addition and multiplication between these complex objects (having one real number and one imaginary number).

After that, I did the first problem of "Linear algebra and its applications", and my tension as a programmer was so high that I tried the matrix class this time. At this point, I have written a class that finds the product of a quadratic square matrix and a column vector with two components.

Let's write an article as a summary.

Reference site Let's make a matrix class http://syrinx.q.t.u-tokyo.ac.jp/tori/java/basic/Matrix.html

There was an example JavaDoc in the link below, so I wrote the class referring to it. http://syrinx.q.t.u-tokyo.ac.jp/tori/java/basic/MatrixJavaDoc.html

This time it is part 1, so I will write about addition and subtraction. In this article, I take the programming style of writing JavaDoc first and then implementing the program. In XP (Extreme Programming), I will write from the test code, but this time there was just the right JavaDoc in the link above, so I implemented it based on JavaDoc.

Code below The last q in Matrixq is Qiita.

//ここはコードとして挿入されていませんが、コードをもし実行するならば、大事な宣言です。ただコメントなど日本語で加筆したこともあり、エラーが出るかもしれません。 // // An instance variable called private double [] [] double2DArray is also a required declaration.

public class Matrixq { private double[][] double2DArray; //Constructor

Matrixq (int rowSize, int columnSize) // This is a constructor that creates an object of Matrixq class //行と列のサイズを受け取ります { double2DArray=new double[rowSize][columnSize]; }

Matrixq (double [] [] mat2Darray) // This is another constructor that creates an object of class Matrixq //double型の二次元配列を受け取ります、その二次元配列を名前mat2Darrayとして扱います //受け取ったその二次元配列を、インスタンス変数double2DArrayに代入します。 //mat2Darrayは、matrix2DimensinalArrayの略です { this.double2DArray=mat2Darray; }

//Instance Methods

double get (int i, int j) // Define get () that returns the elements of mat2Darray [i] [j] of double type array { return double2DArray[i][j]; }

int getRowSize () // return the row size getRowSize () is a method that returns the row size { int l=this.double2DArray.length; return l; }

int getColumnSize () // Returns the column size getColumnSize () is a method that returns the column size { int l=this.double2DArray[0].length; return l; }

So far, I have implemented it from the reference site JavaDoc. If you know the constructor, the point is how to use length () in a two-dimensional array. Also, in Java language, this reference is coming out. I'm using this to access an instance variable of an object in a class. However, the object of that class has not been created yet. Therefore, you cannot use the dot operator "name.variable". this points to an object of this class and is accessing its instance variable in combination with the dot operator.

the first Matrixq(int rowSize,int columnSize) { double2DArray=new double[rowSize][columnSize]; } Then private double[][] double2DArray; Declare the size of a double-type two-dimensional array declared as a private instance variable in. This is the constructor for objects of class Matrixq. This private instance variable called private double [] [] double2DArray will be automatically generated every time you create an object of Matrixq class.

A two-dimensional array is declared with the int type integer rowSize received as an argument and the size of columnSize. The contents of the two-dimensional array generated at this time (values of each element) are all 0.0. It's a Java specification. In other words, if you use a constructor that receives the row size and column size, the initial value of 0.0 is stored in the double type two-dimensional array of the created Matrixq object.

The next constructor (overloading / polymorphism) takes a more practical, content double-type two-dimensional array as an argument and assigns it to the "double2DArray" field of the Matrixq class object.

This field should be accessed with getter (). That is why we have a private declaration.

The rest of the instance methods can be roughly understood by looking at the comments. This is the end of the above code description.

Below static method

//Static Methods
public static Matrixq plus(Matrixq m1,Matrixq m2)
{
	
	isValidMatrix(m1, m2);
	
	Matrixq mAns=new Matrixq(m1.getRowSize(),m1.getColumnSize());

	for(int i=0;i<m1.getRowSize();i++)
	{
		for(int j=0;j<m1.getColumnSize();j++)
		{
			mAns.double2DArray[i][j]=m1.double2DArray[i][j]+m2.double2DArray[i][j];
		}
	}
		
	return mAns;
}

public static Matrixq minus(Matrixq m1,Matrixq m2)
{
	
	isValidMatrix(m1, m2);
	
	Matrixq mAns=new Matrixq(m1.getRowSize(),m1.getColumnSize());

	for(int i=0;i<m1.getRowSize();i++)
	{
		for(int j=0;j<m1.getColumnSize();j++)
		{
			mAns.double2DArray[i][j]=m1.double2DArray[i][j]-m2.double2DArray[i][j];
		}
	}
		
	return mAns;
}

private static void isValidMatrix(Matrixq m1, Matrixq m2) throws MatrixException 
{
	if(m1.getRowSize()!=m2.getRowSize() || m1.getColumnSize()!=m2.getColumnSize())
	{
		throw m1.new MatrixException("Matrix row, column size error. Check size");
	}
}

The algorithm around here is fun for the reader. (Planned to be added) The point is the implementation of exception handling. The isValidMatrix () method verifies that the two matrices (Matrixq objects) to be calculated are of a reasonable size that can be calculated as a matrix. This is a bit difficult, but also a fun part of programming matrix calculations. The derived class "MatrixException" class of RuntimeException is implemented.

Actually, I also made a ColumnVector class, and wrote a class for the product of a quadratic square matrix x a column vector with two components.

It was quite difficult to find the product. I found the formula, tried it in a small procession, and finally tried it. Corrected the part where the relationship between rows and columns is reversed.

...

Recommended Posts

Creating a matrix class in Java Part 1
Creating a matrix class in Java Part 2-About matrices (linear algebra)-
A quick review of Java learned in class part3
Creating lexical analysis in Java 8 (Part 2)
Creating lexical analysis in Java 8 (Part 1)
What is a class in Java language (3 /?)
[Creating] A memorandum about coding in Java
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
A quick review of Java learned in class
Write a class that can be ordered in Java
Write a class in Kotlin and call it in Java
Find a subset in Java
[MQTT / Java] Implemented a class that does MQTT Pub / Sub in Java
3 Implement a simple interpreter in Java
I created a PDF in Java.
StringBuffer and StringBuilder Class in Java
A simple sample callback in Java
Get stuck in a Java primer
I can't create a Java class with a specific name in IntelliJ
About returning a reference in a Java Getter
When seeking multiple in a Java array
Kotlin Class part.2 to send to Java developers
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Java creates a table in a Word document
Java creates a pie chart in Excel
Why does Java call a file a class?
Create a TODO app in Java 7 Create Header
Try making a calculator app in Java
Creating a Servlet in the Liberty environment
Implement something like a stack in Java
Split a string with ". (Dot)" in Java
Creating a project (and GitHub repository) using Java and Gradle in IntelliJ IDEA
Creating a java web application development environment with docker for mac part1
[Java] Implement a function that uses a class implemented in the Builder pattern
I made a primality test program in Java
Java Callback Simple Sample Part2 Anonymous Class Example
Add .gitignore when creating a project in Xcode
Java class methods
Escape processing when creating a URL in Ruby
Two ways to start a thread in Java + @
Create a CSR with extended information in Java
java Scanner class
A story about the JDK in the Java 11 era
Use OpenCV_Contrib (ArUco) in Java! (Part 1-Build) (OpenCV-3.4.4)
Java HashMap class
How to display a web page in Java
Java method call from RPG (method call in own class)
[Android / Java] Operate a local database in Room
Be careful when setting the class name when creating a document-based app in Swift
Measure the size of a folder in Java
Code to escape a JSON string in Java
java (abstract class)
Try to create a bulletin board in Java
Changes in Java 11
Class in Ruby
Rock-paper-scissors in Java
How to get Class from Element in Java
A note when you want Tuple in Java
java practice part 1
I wrote a primality test program in Java