I am pretty new to Java and I am facing an issue I believe it can be mastered pretty easily.
I am generating a project with is linked to the Apache - Commons Math library.
Within the project, I'm making use quite a lot of RealMatrix objects. I have a method working as follows
public static RealMatrix DistCalc(RealMatrix YCoord, RealMatrix ZCoord){
RealMatrix Distance = new Array2DRowRealMatrix(YCoord.getRowDimension(),ZCoord.getRowDimension());
for(int ii = 0; ii < YCoord.getRowDimension(); ii++){
for(int jj = 0; jj < ZCoord.getRowDimension(); jj++){
Distance.setEntry(ii,jj,Math.sqrt((YCoord.getEntry(ii, 0) - YCoord.getEntry(jj, 0))*(YCoord.getEntry(ii, 0) - YCoord.getEntry(jj, 0)) + (ZCoord.getEntry(jj, 0) - ZCoord.getEntry(ii, 0))*(ZCoord.getEntry(jj, 0) - ZCoord.getEntry(ii, 0))));
}
}
return Distance;
}
and another one generating a certain Complex matrix,
// Define the random phase for the u- component
public static Complex[][] RandPhi(int N, int nFFT){
Complex[][] nn_u = new Complex[N][nFFT];
for(int ii = 0; ii < N; ii++){
for(int jj = 0; jj < nFFT; jj++){
nn_u[ii][jj] = new Complex(Math.cos(new Random().nextDouble()*2*Math.PI),Math.sin(new Random().nextDouble()*2*Math.PI));
}
}
return nn_u;
}
Now, I'd like multiplying column-wise the RealMatrix Distance with the Complex matrix nn_u: in the end I should come up with a Complex[N][nFFT] matrix.
Would you mind to shed some light?
I recommend that you create your own ComplexMatrix interface based on the RealMatrix interface, and that you then create your own Array2DRowComplexMatrix class based on the Array2DRowRealMatrix class. To create the class, simply download the source code, change the class name, change double data[][] to Complex data[][], and then update all references to data.
Either create a ComplexMatrix constructor that accepts a RealMatrix, or else include a multiply method with a RealMatrix parameter.
Commons should have all of the methods you need, you might just need to tweak their parameter/return types a bit.
Related
I#m trying to model the objective function sum(i in Sites,j in Sites, k in Routings)(c[i][j] * x[i][j][k]*TruckKmCost) in Cplex using java.
IloLinearNumExpr expr = cplex.linearNumExpr();
for (int i = 1; i <= nbFarmer; i++) {
for (int j = 1; j <= nbFarmer; j++) {
for (int k = 1; k <= nbRouting; k++) {
expr.addTerm(truckKmCost, c[i][j],x[i][j][k]);
}
}
}
This was my attempt, but the method addTerm only accepts (double, IloNumVar), and I can't convert c[i][j] to IloNumVar, because I need it as an int so i can add my int values to it.
There must be a pretty easy solution, maybe somebody can help me, I'm a little stumped right now.
Thanks a lot!
You did not specify whether c[i][j] is a variable or a number. Depending on this there are two different solutions to your issue:
In case c[i][j] is a number then just write expr.addTerm(truckKmCost * c[i][j], x[i][j][k]), that is, merge the two numbers into one single argument to addTerm.
In case c[i][j] is a variable then your objective is not linear but quadratic. In that case you cannot use IloLinearNumExpr but have to use IloQuadNumExpr. The addTerm() of this class takes two variables as arguments.
Being new to algorithms and having searched all over the web, including some answers on stackoverflow, I still find myself asking how I find the distance between those nodes in a simple matrix.
First of all, the simple matrix:
public class MatrixRoutes {
int[][] position; // matrix
int size;
MatrixRoutes(int dimentions) {
posicion = new int[dimentions][dimentions];
size= dimensiones;
}
}
I set the size of the matrix with a simple
MatrixRoutes r = new MatrixRoutes(5);
Cool! I have my empty grid!
Populating it with the most simple of data, distances:
r.position[0][1] = 1;
r.position[1][1] = 0;
r.position[0][2] = 2;
r.position[2][2] = 0;
r.position[0][3] = 3;
r.position[3][3] = 0;
r.position[0][4] = 4;
r.position[4][4] = 0;
r.position[0][5] = 5;
r.position[5][5] = 0;
There's my test distance matrix, all ready to be tested.
Alright, got my nodes with distances. Now it's a matter of finding the shortest distance. I've been reading about different algorithms and their implementations with Java.
I've wanted to implement Dijkstra's algorithm, but it seems to only accept one starting number, used as a distance variable? That's not what I need when I need the distance between two variables.
Here's my attempt at implementing the algorithm:
private static int buscarRutaMasRapida(MatrixRoutes g, int nodeOrigin, int nodeDestiny)
{
int[] found = new int[g.position.length];
boolean[] visitedNode = new boolean[g.position.length];
int max = 999;
for (int i = 0; i < g.position.length; i++)
{
mejor[i] = max;
visitedNode [i] = false;
}
found[nodeOrigin+ nodeDestiny] = nodeOrigin + nodeDestiny;
for(int i = 0; i < g.position.length; i++)
{
int min = max;
int nodoNow = nodeOrigin;
for (int j = 0; j < g.position.length; j++)
{
if (!visitedNode [j] && found [j] < min)
{
nodoNow = j;
min = found [j];
}
}
visitedNode [nodoNow ] = true;
for (int j = 0; j < g.position.length; j++)
{
if (g.position[nodoNow ][j] < max && found[nodoNow ] + g.position[nodoNow ][j] < found [j])
{
found[j] = found [nodoNow ] + g.position[nodoNow ][j];
}
}
}
return found [g.position.length - 2];
}
All I'm asking is someone who would know of an algorithm which would find the shortest distance between two nodes in either a normal adjacency matrix or distance matrix.
Dijkstra's is the (my) preferred route. It takes in one node and finds the shortest path to all other nodes. Usually for distance between two nodes one would create a check inside Dijkstra's to return when the desired "end" node is reached.
In fact, Wikipedia has very nice psuedocode for you to use.
So for instance in the first step of Dijkstra's, you need to find the distance from the origin point S, you would look at all distances from S to other nodes and put this into your priority queue:
queue.add(position[S][x]); //Do this for all x adjacent to S
If you need to store the distance between each point then repeated use of Dijstraka's algorithm is inefficient if the adjacency graph is dense.
Instead you want the Floyd-Warshall algorithm.
From the wikipedia page, Dijstraka's will have a running time of O(V E log V ) while Floyd-Warshall will be O(V^3). In a connected graph E is between V (singly connected) and V^2 (each node connected to every other node), so the best will really depend on your data.
Sorry,this is a homework problem. I am not good with maths, so I checked out some videos to understand how two matrices are multiplied. I came up with a formula, but I do not know what I am doing wrong? This question has been answered before, but I did not understand. Thank you.
case 3:
System.out.println("THE PRODUCT OF TWO MATRICES ARE: ");
for(i =0; i< arrayList.length; i++){
for(j =0; j< arrayList1.length; j++){
for(k =0; k < arrayList1.length;k++){
multiplication = arrayList[i][k] * arrayList1[k][j] + multiplication;
}
System.out.print(arrayList[i][j]+" ");
}
System.out.println();
}
break;
First of all you should understand that the multiplication of two matrices should result in a matrice (which not appear to be the case with your multiplication variable).
I suppose you have to program the basic implementation. Let's take a look at the following matrices.
A has n rows, and m columns; said to be a matrice n x m.
Similary, B has m rows and p columns (m x p matrice). The multiplication of A x B will give you a matrice n x p.
Note that if you want to do the multiplication A x B, the matrice A must have the same number of columns that the number of rows of the matrice B.
Now each value in the matrice AB (ith row and jth column) is computed as follow:
That said, let's take a look at the Java implementation (which is a pure translation of the mathematical formula).
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int[][] result = new int[matrixA.length][matrixB[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
for (int k = 0; k < matrixB.length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
The result matrice is initialized at the right dimensions. Then the first two nested loop (with indices i and j) will loop through all the elements of elements of the resulting matrice. Then you just need the third loop to compute the sum.
You'd still need to check that the matrices you give as parameters have the correct length.
The algorithm used is pretty naive (O(n3) complexity). If you don't understand it, there's a lot of resources in the web that explains how it works; but that would more a mathematical question than a programming one.
Hope it helps ! :)
In c++ we can have this kind of vectors:
vector < int > v[20];
I have to create the equivalent in java of a program in c++. I can declare
static ArrayList < ArrayList<Integer > > v;
but it's not quite what I want. I want it to be more intuitive.
I am trying to find a way to easily add elements in my structure.
For example if I have a graph and I am reading a road from a to b, in C++ a simply use v[a].push_back(b).
First of all vector<int> v[20] is not vectors of vector.
Secondly ArrayList could be the equivalent of std::vectors in Java.
The general equivalent of vector.push_back could be like this ie, using generic list:-
List<Integer> x = new ArrayList<Integer>();
x.add(1);
List<Integer>[] v = (List<Integer>[]) Array.newInstance(Integer.class, 20);
{
for (int i = 0; i < v.length; ++i) {
v[i] = new ArrayList<>();
}
}
Sadly, Java is not so concise or well designed here. Array.newInstance serves for all dimesions: int[][][] would be Array.newInstance(int.class, 10, 10, 10). Hence it returns an Object as least denominator, and needs to be cast.
The initial array contains only nulls, and needs an initialisation.
Correction:
Should of course be List.class not Integer.class.
import java.util.Vector;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new Vector<Integer>();
anArray[2].add(2);//....
}
}
I'm working on an OpenGL project in Java, and it has come to point where I'd like to create the transformation matrices in my own code, so i can use them to do world-to-screen point transformations, and vice versa. I've created a Matrix class with support for transformations, and that is all working quite nicely. However, I'm having trouble actually figuring out how to create an inverse transform.
So my question is this:
Given an arbitrary affine (4x4) transformation matrix, how do you create the inverse transformation matrix? Are some matrices uninvertible? What are the limitations and caveats of inverting a transformation matrix?
From my research, I've heard various methods of doing so, with the simplest being to transpose then negate the matrix. However, this doesn't seem to be actually working. I've heard that this method doesn't work on some matrices, and even that some matrices are uninvertible.
I'm looking for more than just a "plug in this equation" answer, because I'd actually like to understand what's going on when I invert a matrix. This also excludes "just use this library" answers. I might move to a matrix library in the future, but for now I'd like to create it myself.
Edit: Before anyone asks, this is NOT homework. This is a personal project.
Edit: Apparently there's a whole list of strategies for calculating inverse matrices here: http://en.wikipedia.org/wiki/Invertible_matrix
Here is some code that I used in my Computer Graphics course, basically I used the Gauss Jordan elimination for calculating the inverse of a matrix. For a matrix to be invertible its determinant value must be not equal to zero. I have not handled that case in my code though, I am not going to do it all for you.
Matrix4* Matrix4::FindInverse(Matrix4 &a){
int n = R;
int i = 0;
int j = 0;
float pivot = 0;
Matrix4* invA = NULL;
//TODO: Check whether the matrix is invertible.Else Return
invA = new Matrix4();
invA->SetMatrix4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);
for(i = 0; i < n; i++){
pivot = a.v[i][i];
if(pivot != 1.0 and pivot != 0){
for(int t = i; t < n; t++){
a.v[i][t] = a.v[i][t]/pivot;
invA->v[i][t] = invA->v[i][t]/pivot;
}
}
//Update to the new pivot which must be 1.0
pivot = a.v[i][i];
for(j = 0; j < n; j++){
if( j==i ){
continue;
}
else{
float l = a.v[j][i]/pivot;
for(int m = 0; m < n; m++){
a.v[j][m] = a.v[j][m] - l * a.v[i][m];
invA->v[j][m] = invA->v[j][m] - (l * invA->v[i][m]);
}
}
}
}
return invA;
}