Do anybody have a function with which I can transpose a Matrix in Java which has the following form:
double[][]
I have function like this:
public static double[][] transposeMatrix(double [][] m){
for (int i = 0; i < m.length; i++) {
for (int j = i+1; j < m[0].length; j++) {
double temp = m[i][j];
m[i][j] = m[j][i];
m[j][i] = temp;
}
}
return m;
}
but its wrong somewhere.
public static double[][] transposeMatrix(double [][] m){
double[][] temp = new double[m[0].length][m.length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
temp[j][i] = m[i][j];
return temp;
}
If you would like to use an external library, Apache Commons Math provides the utility to transpose a matrix. Please refer to it official site.
First, you have to create a double array double[][] arr, as you have already done. Then, the transposed 2d matrix can be achieved like this
MatrixUtils.createRealMatrix(arr).transpose().getData()
Since Java 8, you can do this:
public static double[][] transposeMatrix(final double[][] matrix) {
return IntStream.range(0, matrix[0].length)
.mapToObj(i -> Stream.of(matrix).mapToDouble(row -> row[i]).toArray())
.toArray(double[][]::new);
}
Java Class to Transpose a matrix :-
import java.util.Scanner;
public class Transpose {
/**
* #param args
*/
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
col = m;
int n = sc.nextInt();
row = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
int[][] trans_arr = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans_arr[j][i] = arr[i][j];
}
}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans_arr[i][j] + " ");
}
System.out.println();
}
}
}
Here is the method
public static double[][] transpose(double arr[][]){
int m = arr.length;
int n = arr[0].length;
double ret[][] = new double[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
ret[j][i] = arr[i][j];
}
}
return ret;
}
Here is a code to transpose a two dimensional matrix "In Place" (not using another data structure to save output) and hence is more memory efficient:
Same below algorithm can be used for int or char or string data types as well.
public static double[][] transposeDoubleMatrix(double[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double tmp = matrix[j][i];
matrix[j][i] = matrix[i][j];
matrix[i][j] = tmp;
}
}
return matrix;
}
Here's a small change!
for (int j = i; j < m[0].length; j++)
Related
Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!
My problem is in my basicsMatrixMain.java code, that I do not know how can I print out thre results I get from difference or transpone. Can anybody help me to solve it ?
public class basicsMatrix {
private final int N;
private final int M;
private final double[][] matrix;
public basicsMatrix(int M, int N) {
this.N = N;
this.M = M;
matrix = new double[M][N];
}
public basicsMatrix(double[][] matrix) {
M = matrix.length;
N = matrix[0].length;
this.matrix = new double[N][M];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.matrix[i][j] = matrix[i][j];
}
public void transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
}
public void add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
}
public void difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
public String matrixtostring(double[][] matrix1){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
sb.append(matrix1);
}
}
return sb.toString();
}
}
public class basicsMatrixMain {
public static void main(String[] args) {
int N = 2;
int M = 3;
double[][] matrix1 = { {2, 3, 4}, {5, 2, 3} };
double[][] matrix2 = { {-4, 5, 3}, {5, 6, 3} };
System.out.println("\n");
System.out.print("Difference:");
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
System.out.println();
}
}
}
}
You have defined a lot of functions in basicsMatrix that you can use here.
However there are some changes that you need to make. In your add, difference and transpose methods, you define something but you never save the result. I would recommend something like this:
public double[][] transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
return transpose;
}
public double[][] add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
return osszeadas;
}
public double[][] difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return kivonas;
}
All these functions now return a matrix that you can print out.
Now you just print you matrices. Something like this should work.
System.out.println(matrixtostring(transzponalas(matrix1)));
System.out.println(matrixtostring(add(matrix1,matrix2)));
System.out.println(matrixtostring(difference(matrix1,matrix2)));
Looking at the question description.
"Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!"
I suspect that you are supposed to create a class that calls functions on itself. In other words the basicsMatrix will become your matrix.
For example, the transzponalas method would become
public void transzponalas(){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = this.matrix[i][j];
}
}
int tmp = this.M
this.M = this.N
this.N = tmp
this.matrix = transpose;
}
This way, you change the matrix that is inside your basicsMatrix. You should make sure that you understand the assignment correctly.
I have created a 5x5 matrix out of random double numbers. I need help to also output the largest element (number) from each row and column. It would output it on a seperate line like "the largest elements in the rows are: [x, x ,x ,x,x] and the same for the columns.
I have tried to create two seperate methods but trying to call them is not working.
public class HomeworkOne {
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double[n][n];
double[] randomArray = new double[n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt() % 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args) {
double[][] matrix = RandomArray(5);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j]);
}
System.out.println("");
}
}
}
I also keep getting the numbers in the matrix crunched up as in their is no space between the numbers. How could I format them to have a space between each number?
You can loop through the columns and rows and find the max; maxRow and maxCol both hold the maximum values, starting at index zero for both (so you know which row and column the max is from).
double[] maxRow = new double[5];
double[] maxCol = new double[5];
double[] row = new double[5];
double[] col = new double[5];
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
row[y] = matrix[x][y];
col[y] = matrix[y][x];
}
Arrays.sort(row, 0, 4);
Arrays.sort(col, 0, 4);
maxRow[x] = row[4];
maxCol[x] = col[4];
}
I also keep getting the numbers in the matrix crunched up as in their is no space between the numbers. How could I format them to have a space between each number?
System.out.print(matrix[i][j] + " ");
import java.util.Random;
public class HomeworkOne{
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
double[] randomArray = new double [n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args){
System.out.println("\u000C");
int size = 5;
double[][] matrix= RandomArray(size);
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
System.out.printf("%6.1f", matrix[i][j]);
}
System.out.println("");
}
maxRow(size,matrix);
maxCol(size,matrix);
}
public static void maxRow(int size,double[][] randomMatrix){
double[] rows = new double[size];
for(int i = 0; i < size; i++){
rows[i] = randomMatrix[i][0];
for(int j = 1; j < size; j++){
if(randomMatrix[i][j] > rows[i]) rows[i] = randomMatrix[i][j];
}
}
System.out.println();
System.out.println("Max Rows");
for(int i = 0; i < size; i++){
System.out.println(i + " " + rows[i]);
}
}
public static void maxCol(int size,double[][] randomMatrix){
double[] cols = new double[size];
for(int j = 0; j < size; j++){
cols[j] = randomMatrix[0][j];
for(int i = 1; i < size; i++){
if(randomMatrix[i][j] > cols[j]) cols[j] = randomMatrix[i][j];
}
}
System.out.println();
System.out.println("Max Cols");
for(int i = 0; i < size; i++){
System.out.printf("%6d",i);
}
System.out.println();
for(int i = 0; i < size; i++){
System.out.printf("%6.1f",cols[i]);
}
}
}
I created a function to multiply a matrix by itself which gets 2 parameters, one is the matrix, the other one is an int n. The problem is that I cant figure out where should I use the n in my code so that it multiplies the matrix by itself an n number of times (in other words matrix^n). At current stage it only does matrix^2;
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * array[x][j];
}
newArray[i][j] = sum;
}
}
return newArray;
}
Add a third for loop that goes from 1 < k < n . You will need to remain array untouched in order to maintain the values of the initial matrix, will also need a matrix newArray to keep the values of the previous multiplication and a temporary matrix tmp that just hold values during the multiplication itself and then is copied to newArray.
Take a look in the sample below.
FULL CODE
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Just holds values during multiplication between two matrices
int[][] tmp = new int[array.length][array.length];
// Initialize newArray to be equal to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
// Outer loop that multiplies as many times as you want
for (int k = 1; k < n; k++) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
tmp[i][j] = sum;
}
}
// Copy the result from multiplication to newArray and restart tmp
System.arraycopy(tmp, 0, newArray, 0, tmp.length);
tmp = new int[array.length][array.length];
}
return newArray;
}
Hope it helped!
You can create two methods for clarity: the first to multiply a square matrix, and the second to call the first n number of times.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = array;
for (int i = 0; i < n; i++) {
newArray = squareMatrixMultiplication(newArray);
}
return newArray;
}
public static int[][] squareMatrixMultiplication(int[][] array) {
int[][] newArray = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
for (int x = 0; x < array.length; x++) {
newArray[i][j] += array[i][x] * array[x][j];
}
}
}
return newArray;
}
Initialize newArray to be equal to array, then
add a loop around the matrix multiplication and use newArray in your nested loops: multiply newArray by array.
public static int[][] lungimeDrumuri(int[][] array, int n) {
int[][] newArray = new int[array.length][array.length];
// Add loops to initialize newArray to array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
newArray[i][j] = array[i][j];
}
}
for (int j = 0; j < n; j++) { // Add this loop
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += newArray[i][x] * array[x][j]; // Use newArray here
}
newArray[i][j] = sum;
}
}
} // and this
return newArray;
}
public class MyClass {
public static void main(String args[]) {
int array[][] = new int[2][2];
array[0][0] = 1;
array[0][1] = 2;
array[1][0] = 3;
array[1][1] = 4;
int newArray[][] = new int[2][2];
//initialize array with these elements
newArray[0][0] = 1;
newArray[0][1] = 0;
newArray[1][0] = 0;
newArray[1][1] = 1;
int n = 5;
for (int i = 0; i < n; i++) {
newArray = lungimeDrumuri(array, newArray, i);
}
}
public static int[][] lungimeDrumuri(int[][] array, int newArray[][], int n) {
int newArray1[][] = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
int sum = 0;
for (int x = 0; x < array.length; x++) {
sum += array[i][x] * newArray[x][j];
}
newArray1[i][j] = sum;
}
}
return newArray1;
}
}
Hope this one will help you.
Can someone help me with something?
I'm trying to convert a string which was initially created using the deepToString() method, back to an array. I've tried pretty much anything I could find on Stack Overflow… but no luck.
This is what I have right now:
import java.util.*;
public class Test3 {
static int matrix [][] = new int[2][2];
public static int[][] matrixGenerator() {
Random r = new Random( );
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static void main(String args[]){
String matrix1 = Arrays.deepToString(matrixGenerator());
String matrix2 = Arrays.deepToString(matrixGenerator());
System.out.println(matrix1 + '\n' + matrix2);
}
}
This outputs
[[6030, 3761], [6605, 5582]]
and
[[1799, 461], [1197, 1012]]
Which is exactly what I need. Now I'm trying to do a matrix multiplication using this piece of code.
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i = 0; i < m1rows; i++) {
for (int j = 0; j < m2cols; j++) {
for (int k = 0; k < m1cols; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
The problem is that I cannot loop through the array because it's not actually an array, it's a string. Which makes sense. Can someone tell me how can I loop, though? I've tried to convert the string back to array - but no luck
Why do you need convertion of matrix to String and then back to matrix?
Can you simply use
public static void main(String[] args) {
int matrix1 [][] = matrixGenerator();
int matrix2 [][] = matrixGenerator();
int matrix3 [][] = matrixMultiplication(matrix1, matrix2);
String matrix1Str = Arrays.deepToString(matrix1);
String matrix2Str = Arrays.deepToString(matrix2);
String matrix3Str = Arrays.deepToString(matrix3);
System.out.println(matrix1Str+'\n'+matrix2Str+'\n'+matrix3Str);
}
public static int[][] matrixGenerator(){
int matrix [][] = new int[2][2];
Random r = new Random( );
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
matrix[i][j] = r.nextInt( 10000 );
}
}
return matrix;
}
public static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) {
int m1rows = matrix1.length;
int m1cols = matrix1[0].length;
int m2cols = matrix2[0].length;
int[][] result = new int[m1rows][m2cols];
for (int i=0; i< m1rows; i++){
for (int j=0; j< m2cols; j++){
for (int k=0; k< m1cols; k++){
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
I was wondering how it was possible to fill a ragged array with a loop in Java.
In my example I want to put Pascals Triangle in the Array. When I try to do it ragged, (
// int [][] hako = new int [n][]; -> as I understand it; it gives a java.lang.NullPointerException.
Thanks
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
static int factorial(int n){
int k = 1;
if(n == 0)
return 1;
while(n>1){
k*=n;
n--;
}
return k;
}
static int newton(int i, int j){
return factorial(i)/((factorial(j))*(factorial(i-j)));
}
You need to initialize hako[i] as an array before you can assign a variable to an index within it i.e. hako[i][j].
int n = 12, r = 1;
int [][] hako = new int [n][];
for(int i = 0; i < n; i++){
for(int j = 0; j < r; j++){
// need to initialize hako[i]
hako[i] = new int[r];
hako[i][j] = newton(i, j);
}
r++;
}
your hako, is a matrix, but you initialize only one dimension thus your NullPointerException
to fix it try
for(int i = 0; i < n; i++){
hako[i] = new int[r];
for(int j = 0; j < r; j++){
hako[i][j] = newton(i, j);
}
r++;
}
public static void main(String[] args) {
int y[][] = new int[4][];
int four =4;
for (int row = 0; row < y.length; row++) {
y[row] = new int[four--];
}
RaggedArray(y);
for (int row = 0; row < y.length; row++) {
for (int column = 0; column < y[row].length; column++) {
System.out.print(y[row][column] + " ");
}
System.out.println();
}
}
public static void RaggedArray(int x[][]) {
int j;
for (int i = 0; i < x.length; i++) {
int k=1;
for (j = 0;j<x[i].length ; j++) {
x[i][j] = k++;
}
}
}}
You can change the size and fill it with any data. I wish it will be useful for u and anyone see this code.