RealMatrix multiply without reassign - java

in my Java source i must execute following lines very often:
vecX = EigenMat.multiply(vecX);
vecY = EigenMat.multiply(vecY);
EigenMat is a N x N Matrix with N~40
vecX/vecY is a N x 1 vector (intern a RealMatrix to)
I used the "Sampler" from VisualFM to find some hotspots in my code and
org.apache.commons.math3.linear.Array2DRowRealMatrix.<init>()
org.apache.commons.math3.linear.Array2DRowRealMatrix.multiply()
have a very high runtime.
I'm not a java professional but i think every multiplication a new vector is created. Can i reassign the old one?
Maybe i should switch to JBLAS to speed it up?
Matyro
Edit:
Single core only

i think every multiplication a new vector is created
Yes, it is. Source code of multiply():
public Array2DRowRealMatrix multiply(final Array2DRowRealMatrix m) {
// Safety check.
MatrixUtils.checkMultiplicationCompatible(this, m);
final int nRows = this.getRowDimension();
final int nCols = m.getColumnDimension();
final int nSum = this.getColumnDimension();
final double[][] outData = new double[nRows][nCols];
// Will hold a column of "m".
final double[] mCol = new double[nSum];
final double[][] mData = m.data;
// Multiply.
for (int col = 0; col < nCols; col++) {
// Copy all elements of column "col" of "m" so that
// will be in contiguous memory.
for (int mRow = 0; mRow < nSum; mRow++) {
mCol[mRow] = mData[mRow][col];
}
for (int row = 0; row < nRows; row++) {
final double[] dataRow = data[row];
double sum = 0;
for (int i = 0; i < nSum; i++) {
sum += dataRow[i] * mCol[i];
}
outData[row][col] = sum;
}
}
return new Array2DRowRealMatrix(outData, false);
}
Input vector m is copied, as stated in a comment Copy all elements of column "col" of "m" so that will be in contiguous memory.
Can i reassign the old one?
Yes, you can perform the multiplication by yourself, writing two loops. Use getData() to get a reference to the underlying double[][] data.

Related

How can I create a new instance of array dynamically if my array size is full in java

I am working on a java program. where I have taken an input string and I am putting each char from a string in a 4*4 matrix. If the input string length is small than 16 i.e 4*4 matrix, then I am adding padding '#' char.
But Now, suppose the input string length is more than 16 then I want to create a new array and put remaining chars into it. I can't use a vector, set, map. So How can I code now?
here is some code. key=4.
char[][] giveMeNewArray() {
char[][] matrix = new char[key][key];
return matrix;
}
void putCharIntoMatrix() {
int counter = 0;
char[][] myArray = giveMeNewArray();
System.out.println("myArray: " + myArray);
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
if (counter >= inputString.length()) {
myArray[i][j] = '#';
} else {
myArray[i][j] = inputString.charAt(key * i + j);
}
counter++;
}
}
for (int i = 0; i < key; i++) {
for (int j = 0; j < key; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
So if I'm understanding this question correctly, you want to create a matrix to hold the characters of an input string, with a minimum size of 4*4?
You're probably better off creating a proper matrix rather than expanding it:
Do you want your matrix to always be square?
Get the next-highest (self-inclusive) perfect square using Math.sqrt
int lowRoot = (int)Math.sqrt(inString.length());
int root;
if(lowRoot * lowRoot < inString.length())
root = lowRoot+1;
else
root = lowRoot;
Create your matrix scaled for your input, minimum four
int size = (root < 4) ? 4 : root;
char[][] matrix = new char[size][size];
But if you really want to expand it, you can just create a new matrix of a greater size:
char[][] newMatrix = new char[oldMatrix.length+1][oldMatrix[0].length+1];
And copy the old matrix into the new matrix
for(int i = 0; i < oldMatrix.length; ++i){
for(int j = 0; j < oldMatrix[i].length; ++j){
newMatrix[i][j] = oldMatrix[i][j];
}
}
If you expand by one each time you'll do tons of expands, if you expand by more you might expand too far.
This is really inefficient versus just doing some math at the beginning. Making a properly sized matrix from the start will save you a bunch of loops over your data and regularly having two matrices in memory.
If understand you request correctly, if the string length is bigger than 16 you just create a new array, well how about making a list of array initilized at one array and if there are more than 16 chars just add an array to the list using your method that returns an array.

Transferring the contents of a one-dimensional array to a two-dimensional array

I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}

multiply a 2d array by a 1d array

I've initialized a 1d and 2d array and now I basically just want to be able to perform matrix multiplication on them. However, I'm not quite getting the proper answer. I think I've mixed up the for loop where I try to ensure I only multiply the correct values, but can't quite get the hang of it.
edit: I've fixed it, I was misunderstanding what the length method of a 2D array returned (thought it returned columns and not rows). The below code is my corrected code. Thanks everyone.
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D[0].length;
double[] newArray = new double[array2D[0].length]; // create the array that will contain the result of the array multiplication
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[j][i];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
There are some problems, first of all, you should decide how the vectors represented, are you multiplying from left or right.
For the maths: vector 1xn times matrix nxm will result in 1xm, while matrix mxn times nx1 result in mx1.
I think the following would work for you:
public static double[] getOutputArray(double[] array1D, double[][] array2D) {
int oneDLength = array1D.length;
int twoDLength = array2D.length;
double[] newArray = new double[twoDLength]; // create the array that will contain the result of the array multiplication
assert twoDLength >0 && array2D[0].length == oneDLength;
for (int i = 0; i < twoDLength; i++) { // use nested loops to multiply the two arrays together
double c = 0;
for (int j = 0; j < oneDLength; j++) {
double l = array1D[j];
double m = array2D[i][j];
c += l * m; // sum the products of each set of elements
}
newArray[i] = c;
}
return newArray; // pass newArray to the main method
} // end of getOutputArray method
I hope I did not make a mistake, while trying to fix.

Java array turning to zeros after exiting a for loop

I'm using an FFT class I found online to compute the FFT of an image. Here's the code to compute the FFT.
w (width) and h (height) are the same value in this instance.
FFT2 fft = new FFT2(w);
double[] realRow = new double[w];
double[] imagRow = new double[w];
double[][] realVals1 = new double[w][h];
double[][] imagVals1 = new double[w][h];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
pixel = bmporiginal.getPixel(x, y);
R = (int) (Color.red(pixel));
G = (int) (Color.green(pixel) );
B = (int) (Color.blue(pixel));
I = ((R+G+B)/3);
I *= Math.pow(-1, (x+y) % 2.0 );
realRow[x] = I;
imagRow[x] = 0.0;
}
fft.fft(realRow, imagRow);
realVals1[y] = realRow;
imagVals1[y] = imagRow;
}
The values I need are being stored in realVals and ImagVals. I can print these values within the for loop and get good values. After leaving the for loops I print them again, and get nothing!!! What could be the problem? I appreciate your help!
You're reusing the same row arrays for every iteration of the loop.
So at the end of the two loops, your realVals1 and imagVals1 will each have h references to the same array. You need to create a new array on each iteration of the outer loop:
for (int y = 0; y < h; y++)
{
double[] realRow = new double[w];
double[] imagRow = new double[w];
for (int x = 0; x < w; x++)
{
...
}
fft.fft(realRow, imagRow);
realVals1[y] = realRow;
imagVals1[y] = imagRow;
}
Additionally, I believe your declarations for realVals1 and imagVals1 are a) inefficient and b) the wrong way round. I suspect you want:
double[][] realVals1 = new double[h][];
double[][] imagVals1 = new double[h][];
You're going to be replacing the elements anyway, so there's no point in populating a bunch of empty rows...
You're reusing the same array realRow and imagRow each time through the inner loop. Since Java works with references, when you assign realVals1[y]=realRow, you assign a reference. Since you always use the same array, you assign all the rows to the same array reference. Which is not what you want. You need to recreate realRow and imagRow to a new double[] at the top of the outer for loop.

How do i print the columns of a JAMA matrix?

I use the JAMA.matrix package..how do i print the columns of a matrix
The easiest way would probably be to transpose the matrix, then print each row. Taking part of the example from the API:
double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
Matrix a = new Matrix(vals);
Matrix aTransposed = a.transpose();
double[][] valsTransposed = aTransposed.getArray();
// now loop through the rows of valsTransposed to print
for(int i = 0; i < valsTransposed.length; i++) {
for(int j = 0; j < valsTransposed[i].length; j++) {
System.out.print( " " + valsTransposed[i][j] );
}
}
As duffymo pointed out in a comment, it would be more efficient to bypass the transposition and just write the nested for loops to print down the columns instead of across the rows. If you need to print both ways that would result in twice as much code. That's a common enough tradeoff (speed for code size) that I leave it to you to decide.
You can invoke the getArray() method on the matrix to get a double[][] representing the elements.
Then you can loop through that array to display whatever columns/rows/elements you want.
See the API for more methods.
public static String strung(Matrix m) {
StringBuffer sb = new StringBuffer();
for (int r = 0; r < m.getRowDimension(); ++ r) {
for (int c = 0; c < m.getColumnDimension(); ++c)
sb.append(m.get(r, c)).append("\t");
sb.append("\n");
}
return sb.toString();
}

Categories

Resources