Snifflib Numerical Library Wiki
Open-source computational library written in pure JAVA
Brought to you by:
mock_turtle
In this tutorial, we will discuss how to work with vectors (a.k.a. N-tuples) and their multi-dimensional extensions matrices.
We'll focus on constructing the following 3x3 matrix:
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
Here are some different examples of syntax to do just that. You may run this code snippet within your own JAVA main() program, Groovy script, etc. For a review of how to get started see Basic Usage;
import com.mockturtlesolutions.snifflib.datatypes.DblMatrix; . . . //Construction from a String. Here are the guidelines... // * Square brackets indicated concatenation. // * Commas and/or spaces indicate column increment. // * Semicolons indicate row increment. DblMatrix X = new DblMatrix("[1 2 3; 4 5 6; 7 8 9]"); X.show("X"); //Concatenation of rows... DblMatrix Y = new DblMatrix("[1 2 3]"); Y = Y.concat(new DblMatrix("[4 5 6]",1); Y = Y.concat(new DblMatrix("[7 8 9]",1); Y.show("Y is just like X"); //Concatenation of columns... DblMatrix Z = new DblMatrix("[1; 4; 7]"); Z = Z.concat(new DblMatrix("[2;5;8]"),2); Z = Z.concat(new DblMatrix("[3;6;9]"),2); Z.show("Another matrix..."); //Fill-in following the assumed "row-first" ordering... int[] siz = new int[]{3,3}; //Note, in Groovy you'd create an int[] using the syntax //def siz = [3,3] as int[]; W = new DblMatrix(siz); for (int k=0;k<9;k++) { W.setDoubleAt(new Double(k+1),k); } W = W.transpose(); W.show("W looks nice!","0"); //Notice that the last show() uses a formatted display for single-digit integers.
Here are some commonly used matrix algebra operations using the DblMatrix class.
import com.mockturtlesolutions.snifflib.datatypes.DblMatrix; . . . DblMatrix X = new DblMatrix("[1 2 3; 4 5 6; 7 8 9]"); X.show("X"); //Create an 3x3 identity matrix. DblMatrix F = DblMatrix.I(3); F.show("Identity matrix"); //Inner product between two matrices. P = W.dot(F); P.show("P") //Element-by-element multiplication between two matrices. Q = W.times(F); Q.show("Q") //Addition of two matrices. M = P.plus(Q); M.show("Addition"); //Subtraction of two matrices. M = P.minus(Q); M.show("Subtraction"); //Element-by-element powering of one matrix by another. M = P.pow(Q); M.show("Power");
To see the many more class methods possible, see the DblMatrix API .