B4A Library JAMA - A Java Matrix Package (B4A Wrapper in post #3)

This is not a wrapper for the JAMA project but nevertheless a JAR and XML that I have created with Simple Library Compiler (SLC) so that JAMA can be used within a B4A project by making use of inline Java Code. The inline Java code (called via B4A library JavaObject) interfaces with the JAR that was created. I have not added B4A code and inline Java code to make use of all the methods. Only most of the constructors and some methods. The purpose of this exercise was to get the interface to work. It should now be simple to add the remaining methods in Matrix.java (see the attached Java code) to make use of all of the methods in Matrix.java. You can add the remainder of the methods in Matrix.java in the same way as what I have added some of the other methods. It is not difficult - fairly simple to do.

I have compiled Jama-1.0.3 into a B4A compatible library (with SLC) so that it can be used with inline Java Code. You therefore need B4A version >= 4.30.

I attach the following:

The JAR and XML created with SLC (B4ALibraryFiles.zip). Copy them to your additional library folder.
The Java Code that was compiled to create the JAR and XML
A screenshot of how I have set up SLC (you need to browse to the folder that holds the src folder)
The B4A project that uses and demonstrates the compiled library and how to use it with inline Java code.

Some sample code:

B4X:
#Region  Project Attributes
    #ApplicationLabel: JHSJAMA
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
    #AdditionalJar:JHSJAMA
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the a
    Dim jo As JavaObject

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.


End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    jo.InitializeContext

'***********************************************************************************************   
    jo.RunMethod("initialize2", Array(4,4,3.0))
    jo.RunMethod("times", Array(4.0))

'*************************************************************************************************   
    Dim c(5,4) As Double
    Log(" ")
    For i = 0 To 4
        For j = 0 To 3
          c(i,j) = Rnd(0,100)
          Log(c(i,j))
        Next       
    Next
    Log(" ")
    jo.RunMethod("initialize3", Array(c))
   
'*************************************************************************************************
    Dim d(5,4) As Double
    Log(" ")
    For i = 0 To 4
        For j = 0 To 3
          d(i,j) = Rnd(0,100)
          Log(d(i,j))
        Next       
    Next
    Log(" ")
    jo.RunMethod("initialize4", Array(d, 3, 2))   
   
'*************************************************************************************************
    Dim e(20) As Double
    Log(" ")
    For i = 0 To 19
      e(i) = Rnd(0,100)
      Log(e(i))
    Next
    Log(" ")
    jo.RunMethod("initialize5", Array(e,5))       
    Dim a(3,3) As Double
    Log(" ")
    a = jo.RunMethod("identity", Array(3,3))
    For i = 0 To 2
        For j= 0 To 2
          Log(a(i,j))
        Next   
    Next

'************************************************************************************************   
    Dim b(4,3) As Double
    Log(" ")
    b = jo.RunMethod("random", Array(4,3))
    For i = 0 To 3
        For j= 0 To 2
          Log(b(i,j))
        Next   
    Next
   
'************************************************************************************************
    Dim f(4,3) As Double
    Log(" ")
    For i = 0 To 3
        For j = 0 To 2
          f(i,j) = Rnd(0,100)
          Log(f(i,j))
        Next       
    Next
    Log(" ")
    jo.RunMethod("initialize3", Array(f))
    Log(" ")
    Dim clmn() As Double
    clmn = jo.RunMethod("getColumnPackedCopy", Null)
    For i = 0 To 11
        Log(clmn(i))
    Next
   
    Log(" ")
     Dim rw() As Double
    rw = jo.RunMethod("getRowPackedCopy", Null)
    For i = 0 To 11
        Log(rw(i))
    Next   
   
    Log(" ")
    Log(jo.RunMethod("getRowDimension", Null))
    Log(jo.RunMethod("getColumnDimension", Null))
   
'************************************************************************************************
   
 
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

#If Java

//this import needs to be here to call the methods in the Matrix class
import Jama.Matrix;
Matrix mm = null;


/** Construct an m-by-n matrix of zeros.
@param m    Number of rows.
@param n    Number of colums.
*/
public void initialize1 (int m, int n) {
  mm = new Matrix(m,n);
}

//*********************************************************************************************

/** Construct an m-by-n constant matrix.
@param m    Number of rows.
@param n    Number of colums.
@param s    Fill the matrix with this scalar value.
*/
public void initialize2 (int m, int n, double s) {
  mm = new Matrix(m,n,s);
}

//*********************************************************************************************

/** Construct a matrix from a 2-D array.
@param A    Two-dimensional array of doubles.
@exception  IllegalArgumentException All rows must have the same length
@see        #constructWithCopy
*/
public void initialize3 (double[][] A) {
  mm = new Matrix(A);
  double[][] C = mm.getArray();
  for (int i = 0; i < C.length; i++) {
    for (int j = 0; j < C[0].length; j++) {
      BA.Log("" + C[i][j]);
    }
  }
}

//*********************************************************************************************

/** Construct a matrix quickly without checking arguments.
@param A    Two-dimensional array of doubles.
@param m    Number of rows.
@param n    Number of colums.
*/
public void initialize4 (double[][] A, int m, int n) {
  mm = new Matrix(A, m, n);
  double[][] C = mm.getArray();
  for (int i = 0; i < C.length; i++) {
    for (int j = 0; j < C[0].length; j++) {
      BA.Log("" + C[i][j]);
    }
  } 
}

//*********************************************************************************************

/** Construct a matrix from a one-dimensional packed array
@param vals One-dimensional array of doubles, packed by columns (ala Fortran).
@param m    Number of rows.
@exception  IllegalArgumentException Array length must be a multiple of m.
*/
public void initialize5 (double vals[], int m) {
   mm = new Matrix(vals,m);
   double[][] C = mm.getArray();
   for (int i = 0; i < C.length; i++) {
     for (int j = 0; j < C[0].length; j++) {
       BA.Log("" + C[i][j]);
     }
   }    
}

//*********************************************************************************************

/** Multiply a matrix by a scalar, C = s*A
@param s    scalar
@return     s*A
*/
public void times(double paramDouble){
  mm = mm.times(paramDouble);
  double[][] C = mm.getArray();
  BA.Log("" + C[0][0]);
}

//*********************************************************************************************

/** Generate identity matrix
@param m    Number of rows.
@param n    Number of colums.
@return     An m-by-n matrix with ones on the diagonal and zeros elsewhere.
*/
public double[][] identity (int m, int n) {
  Matrix a;
  a = mm.identity(m,n);
  double[][] C = a.getArray();
  return C;
}

//*********************************************************************************************

/** Generate matrix with random elements
@param m    Number of rows.
@param n    Number of colums.
@return     An m-by-n matrix with uniformly distributed random elements.
*/
public double[][] random (int m, int n) {
  Matrix a;
  a = mm.random(m,n);
  double[][] C = a.getArray();
  return C;
}

//*********************************************************************************************

/** Make a one-dimensional column packed copy of the internal array.
@return     Matrix elements packed in a one-dimensional array by columns.
*/
public double[] getColumnPackedCopy () {
   double[] a;
   a = mm.getColumnPackedCopy();
   return a;
}

//*********************************************************************************************

/** Make a one-dimensional row packed copy of the internal array.
@return     Matrix elements packed in a one-dimensional array by rows.
*/
public double[] getRowPackedCopy () {
   double[] a;
   a = mm.getRowPackedCopy();
   return a;
}

//*********************************************************************************************

/** Get row dimension.
@return     m, the number of rows.
*/
public int getRowDimension () {
   return mm.getRowDimension ();
}

//*********************************************************************************************

/** Get column dimension.
@return     n, the number of columns.
*/
public int getColumnDimension () {
   return mm.getColumnDimension ();
}


#End If

1.png


I will assist where I can for whoever wants to add the remaining methods in Matrix.java to this B4A project should you need some assistance. But if you follow the B4A code, the inline Java code, and the code in Matrix.java then you should have no problem to add the remaining methods.

Enjoy! ;)
 

Attachments

  • TheJavaCode.zip
    42.4 KB · Views: 382
  • b4aJAMAMatrix.zip
    7.8 KB · Views: 374
  • B4ALibraryFiles.zip
    23.8 KB · Views: 399
  • OriginalJamaJavaFiles.zip
    107.1 KB · Views: 364
Last edited:

Johan Schoeman

Expert
Licensed User
Longtime User
Looks Great ! Thanks Johan, I shall try the library during the coming week.
Here is a B4A wrapper for the JAMA Matrix Package. Posting the following:
1. The B4A library files.
2. The Java Source Code (src.zip)
3. A B4A project demonstrating some of the methods in JAMA. Have wrapped all the methods except for the decompositions (still need to figure out how to do/test the decompositions as it has been many years since I have last studied matrices - like in 1983 to 1987).

It prints the results of the methods used in the B4A project to the B4A log.

JHSJAMA
Author:
Johan Schoeman
Version: 1
  • JamaMatrix
    Methods:
    • GetMatrixEntries As Double[][]
      Return the elements of the matrix as a two-dimensional array of doubles.
    • GetSubMatrix1 (i0 As Int, i1 As Int, j0 As Int, j1 As Int) As JamaWrapper
      Get a submatrix.
      i0 Initial row index
      i1 Final row index
      j0 Initial column index
      j1 Final column index
      return A(i0:i1,j0:j1)
    • GetSubMatrix2 (r() As Int, c() As Int) As JamaWrapper
      Get a submatrix.
      r Array of row indices.
      c Array of column indices.
      return A(r( : ),c( : ))
    • GetSubMatrix3 (i0 As Int, i1 As Int, c() As Int) As JamaWrapper
      Get a submatrix.
      i0 Initial row index
      i1 Final row index
      c Array of column indices.
      return A(i0:i1,c( : ))
    • GetSubMatrix4 (r() As Int, j0 As Int, j1 As Int) As JamaWrapper
      Get a submatrix.
      r Array of row indices.
      j0 Initial column index
      j1 Final column index
      return A(r( : ),j0:j1)
    • Initialize1 (m As Int, n As Int)
      Construct an m-by-n matrix of zeros.
      m Number of rows.
      n Number of colums.
    • Initialize2 (m As Int, n As Int, s As Double)
      Construct an m-by-n constant matrix.
      m Number of rows.
      n Number of colums.
      s Fill the matrix with this scalar value.
    • Initialize3 (A() As Double)
      Construct a matrix from a 2-D array.
      A Two-dimensional array of doubles.
    • Initialize4 (A() As Double, m As Int, n As Int)
      Construct a matrix quickly without checking arguments.
      A Two-dimensional array of doubles.
      m Number of rows.
      n Number of colums.
    • Initialize5 (vals() As Double, m As Int)
      Construct a matrix from a one-dimensional packed array
      vals One-dimensional array of doubles, packed by columns (ala Fortran).
      m Number of rows.
    • Norm1 As Double
      One norm
      return maximum column sum.
    • Norm2 As Double
      Two norm
      return maximum singular value.
    • NormF As Double
      Frobenius norm
      return sqrt of sum of squares of all elements.
    • NormInf As Double
      Infinity norm
      return maximum row sum.
    • ReturnSingleElement (i As Int, j As Int) As Double
      Return a single element (type Double)
      i Row index.
      j Column index.
      return A(i,j)
    • SetSingleElement (i As Int, j As Int, s As Double)
      Set a single element.
      i Row index.
      j Column index.
      s A(i,j).
    • SetSubMatrix1 (i0 As Int, i1 As Int, j0 As Int, j1 As Int, X As JamaWrapper)
      Set a submatrix.
      i0 Initial row index
      i1 Final row index
      j0 Initial column index
      j1 Final column index
      X A(i0:i1,j0:j1)
    • SetSubMatrix2 (r() As Int, c() As Int, X As JamaWrapper)
      Set a submatrix.
      r Array of row indices.
      c Array of column indices.
      X A(r( : ),c( : ))
    • SetSubMatrix3 (r() As Int, j0 As Int, j1 As Int, X As JamaWrapper)
      Set a submatrix.
      r Array of row indices.
      j0 Initial column index
      j1 Final column index
      X A(r( : ),j0:j1)
    • SetSubMatrix4 (i0 As Int, i1 As Int, c() As Int, X As JamaWrapper)
      Set a submatrix.
      i0 Initial row index
      i1 Final row index
      c Array of column indices.
      X A(i0:i1,c( : ))
    • Transpose As JamaWrapper
      Matrix transpose.
      return A'
    • arrayLeftDivide (B As JamaWrapper) As JamaWrapper
      Element-by-element left division, C = A.\B
      B another matrix
      return A.\B
    • arrayLeftDivideEquals (B As JamaWrapper) As JamaWrapper
      Element-by-element left division in place, A = A.\B
      B another matrix
      return A.\B
    • arrayRightDivide (B As JamaWrapper) As JamaWrapper
      Element-by-element right division, C = A./B
      B another matrix
      return A./B
    • arrayRightDivideEquals (B As JamaWrapper) As JamaWrapper
      Element-by-element right division in place, A = A./B
      B another matrix
      return A./B
    • arrayTimes (B As JamaWrapper) As JamaWrapper
      Element-by-element multiplication, C = A.*B
      B another matrix
      return A.*B
    • arrayTimesEquals (B As JamaWrapper) As JamaWrapper
      Element-by-element multiplication in place, A = A.*B
      B another matrix
      return A.*B
    • condition As Double
      Matrix condition (2 norm)
      return ratio of largest to smallest singular value.
    • constructWithCopy (A() As Double) As JamaWrapper
      Construct a matrix from a copy of a 2-D array.
      A Two-dimensional array of doubles.
    • copy As JamaWrapper
      Make a deep copy of a matrix
    • det As Double
      Matrix determinant
      return determinant
    • identity (m As Int, n As Int) As JamaWrapper
      Generate identity matrix
      m Number of rows.
      n Number of colums.
      return An m-by-n matrix with ones on the diagonal and zeros elsewhere.
    • inverse As JamaWrapper
      Matrix inverse or pseudoinverse
      return inverse(A) if A is square, pseudoinverse otherwise.
    • minus (B As JamaWrapper) As JamaWrapper
      C = A - B
      B another matrix
      return A - B
    • minusEquals (B As JamaWrapper) As JamaWrapper
      A = A - B
      B another matrix
      return A - B
    • plus (B As JamaWrapper) As JamaWrapper
      C = A + B
      B another matrix
      return A + B
    • plusEquals (B As JamaWrapper) As JamaWrapper
      A = A + B
      B another matrix
      return A + B
    • random (m As Int, n As Int) As JamaWrapper
      Generate matrix with random elements
      m Number of rows.
      n Number of colums.
      return An m-by-n matrix with uniformly distributed random elements.
    • rank As Int
      Matrix rank
      return effective numerical rank, obtained from SVD.
    • solve (B As JamaWrapper) As JamaWrapper
      Solve A*X = B
      B right hand side
      return solution if A is square, least squares solution otherwise
    • solveTranspose (B As JamaWrapper) As JamaWrapper
      Solve X*A = B, which is also A'*X' = B'
      B right hand side
      return solution if A is square, least squares solution otherwise.
    • timesByMatrix (B As JamaWrapper) As JamaWrapper
      Linear algebraic matrix multiplication, A * B
      B another matrix
      return Matrix product, A * B
    • timesByScalar (s As Double) As JamaWrapper
      Multiply a matrix by a scalar, C = s*A
      s scalar
      return s*A
    • timesEquals (s As Double) As JamaWrapper
      Multiply a matrix by a scalar in place, A = s*A
      s scalar
      return replace A by s*A
    • trace As Double
      Matrix trace.
      return sum of the diagonal elements.
    • uminus As JamaWrapper
      Unary minus
      return -A
    Properties:
    • ArrayCopy() As Double [read only]
      Copy the internal two-dimensional array.
      return Two-dimensional array copy of matrix elements.
    • ColumnDimension As Int [read only]
      Get column dimension.
      return n (an int), the number of columns.
    • ColumnPackedCopy() As Double [read only]
      Make a one-dimensional column packed copy of the internal array.
      return Matrix elements packed in a one-dimensional array by columns.
      The returned one-dimensional array is of type Double
    • RowDimension As Int [read only]
      Get row dimension.
      return m (an int), the number of rows.
    • RowPackedCopy() As Double [read only]
      Make a one-dimensional row packed copy of the internal array.
      return Matrix elements packed in a one-dimensional array by rows.
      The returned one-dimensional array is of type Double
 

Attachments

  • b4aJamaMatrixWrapped.zip
    8.5 KB · Views: 345
  • B4ALibFiles.zip
    23.8 KB · Views: 354
  • src.zip
    24.1 KB · Views: 341
Last edited:

PABLO2013

Well-Known Member
Licensed User
Longtime User
regards
you define in your project in the java object matrix mm ...... but as you could do this in a general way , what I want is sent from BA4 the name of the matriz or that way could use to create several matrices with the same code and methods and other work based on the name of the matrix, thanks


jo.RunMethod("initialize2", .......

//*********************************************************************************************

/** Construct an m-by-n constant matrix.
@param m Number of rows.
@param n Number of colums.
@param s Fill the matrix with this scalar value.
*/
public void initialize2 (int m, int n, double s) {
mm = new Matrix(m,n,s);
}

//*********************************************************************************************
 

PABLO2013

Well-Known Member
Licensed User
Longtime User
I know you have no time , and apology
I think this library .... can not be used directly in BA4 only by the help of JavaObject (ej: jo.RunMethod("initialize3", Array(f))) , I can not start varibles , such as dim as JHSJAMA ...I believe...as access methods and properties that you publish #3

gracias por tus librerias
 

Johan Schoeman

Expert
Licensed User
Longtime User
I know you have no time , and apology
I think this library .... can not be used directly in BA4 only by the help of JavaObject (ej: jo.RunMethod("initialize3", Array(f))) , I can not start varibles , such as dim as JHSJAMA ...I believe...as access methods and properties that you publish #3

gracias por tus librerias
I have added the below code in the B4A project for Initialize3 and it works perfectly....
B4X:
'********************************************************** 

    Log("INITIALIZE3")
    Dim array2d(2,2) As Double
    For i = 0 To 1
        For j = 0 To 1
          array2d(i,j) = Rnd(0,21)
        Next 
    Next
    matrix1.Initialize3(array2d)
 
    Dim bbb(2,2) As Double
    bbb = matrix1.GetMatrixEntries
    For i = 0 To 1
        For j = 0 To 1
            Log(bbb(i,j))
        Next 
    Next 
    Log(" ")
    Log(" ")
    
'**********************************************************
 
Last edited:

PABLO2013

Well-Known Member
Licensed User
Longtime User
regards
Sorry, you're right ... only days ago try a thousand ways to make it work without success ... I should be consulted more , apologies
 

PABLO2013

Well-Known Member
Licensed User
Longtime User
Regards
How i can implement a array of matrix
Ej.
For i = 0 to 3
Matrix(i).iniciatize3(....)
Next
.......

For i=0 to 3
....=Matriz(i).getMatrixentries
Next

Tks in advanced
 

Johan Schoeman

Expert
Licensed User
Longtime User
Regards
How i can implement a array of matrix
Ej.
For i = 0 to 3
Matrix(i).iniciatize3(....)
Next
.......

For i=0 to 3
....=Matriz(i).getMatrixentries
Next

Tks in advanced

B4X:
Dim matrix(3) as JHSJAMA
For k = 0 to 2
    Dim array2d(2,2) As Double
    For i = 0 To 1
        For j = 0 To 1
          array2d(i,j) = Rnd(0,21)
        Next
    Next
    matrix(i).Initialize3(array2d)
    Dim bbb(2,2) As Double
    bbb = matrix(i).GetMatrixEntries
    For i = 0 To 1
        For j = 0 To 1
            Log(bbb(i,j))
        Next
    Next
    Log(" ")
    Log(" ")
Next
 

JNG

Member
Licensed User
Dear Johan,

Thanks for this You are too.................Intelligent.
GOD BLESS YOU
For U Johan
TIME & SMILE are two critical things in life..
Sometimes TIME makes you forget how to SMILE
and
Sometimes someone's SMILE makes us forget TIME....
Be happy and make others feel Happy.

warmly
 

PABLO2013

Well-Known Member
Licensed User
Longtime User
regards
I continued with my project but I have a couple of questions:

1. If I create two matrix (1 and 2) independent and want to change only a data from matrix (1) the program changes the same data in both matrix (1 and 2). I think the problem is that both are filled with the same array (integer = 1) example:

Creating array :

Dim alternativas(nalternativasi,nalternativasj) AsDouble 'nalternativasi=nalternativasj=2


For nalternativasi = 0 to nalternativasi-1

For nalternativasj = 0 to nalternativasj-1

alternativas(nalternativasi,nalternativasj) = 1 'entero

Next

Next

Creation of matrices

For ncriterios = 0 To ncriterios-1 'ncriterios = 2
arr (ncriterios) .Initialize3 (alternativas)
Next

Try this one, and it works independently (i like),but I want to work as a general arrangement(as in the first case) and changing a value of the desired matrix (alone) and not of the rest matrixs ...

Dim alt1 (nalternativasi, nalternativasj) As Double
For nalternativasi = 0 To nalternativasi-1
For nalternativasj = 0 To nalternativasj-1
alt1 (nalternativasi, nalternativasj) = 1
Next
Next

Dim alt2 (nalternativasi, nalternativasj) As Double
For nalternativasi = 0 To nalternativasi-1
For nalternativasj = 0 To nalternativasj-1
alt2 (nalternativasi, nalternativasj) = 1
Next
Next

arr (0) .Initialize3 (alt1)
arr (1) .Initialize3 (alt2)

Thank you
 
Top