Java deepToString to array - matrix multiplication - java

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;
}

Related

How can I print out the result matrix in my java code?

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.

How to implement a method to find the largest element of each row and column in my 5x5 matrix?

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]);
}
}
}

Filling a ragged array with a loop in java

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.

transpose double[][] matrix with a java function?

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++)

How do we rotate a tetris piece counter clockwise?

I looked at the algorithm here for clockwise rotation, but I can't do it the other way around. So basically, for clockwise rotation, you need to multiply the transpose to a rotation matrix, but how do you do the same thing the other way around?
Here's my code:
public class rotation2 {
public static int [][] multiplyMatrix(int [][] m1) {
int [][] m2 = {{0,0,0,1},
{0,0,1,0},
{0,1,0,0},
{1,0,0,0}};
int[][] result = new int[4][4];
// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
public static int [][] multiplyMatrix2(int [][] m2) {
int [][] m1 = {{0,0,0,1},
{0,0,1,0},
{0,-1,0,0},
{-1,0,0,0}};
int[][] result = new int[4][4];
// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
result[i][j] += m1[i][k] * m2[k][j];
return result;
}
public static void printArray(int [][] array) {
for(int row = 0; row < array.length; row++) {
for(int col = 0; col < array[row].length; col++) {
if (array[row][col] > 0) {
System.out.printf("1");
} else {
System.out.printf("0");
}
}
System.out.printf("\n");
}
}
public static int [][] transpose(int [][] m1) {
int m = 4;
int n = 4;
int c = 0;
int d = 0;
int[][] transpose = new int [n][m];
for ( c = 0 ; c < m ; c++ ) {
for ( d = 0 ; d < n ; d++ ) {
transpose[d][c] = m1[c][d];
}
}
return transpose;
}
public static void main(String[] args) {
int [][] m1 = {{1,0,0,0},
{1,0,0,0},
{1,1,0,0},
{0,0,0,0}};
int [][] transpose = transpose(m1);
printArray(transpose);
transpose = multiplyMatrix(transpose);
printArray(transpose);
int [][] transpose2 = transpose(m1);
printArray(transpose2);
transpose2 = multiplyMatrix(transpose2);
printArray(transpose2);
}
}
You don't transpose for counter clock rotation, right?
What you have to do is to (1) transpose the matrix, and (2) inverse the rows (clockwise) or columns (counter-clockwise), respectively.
You can just use a double-for-loop to set the new values for the individual cells, doing both steps at the same time. In code, this might look like this:
public static int[][] rotate(int[][] m, boolean left) {
int rows = m.length, cols = m[0].length;
int[][] m2 = new int[cols][rows]; // swap rows and cols
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (left) // rotate left
m2[c][r] = m[r][cols - c - 1];
else // rotate right
m2[c][r] = m[rows - r - 1][c];
return m2;
}
For more information and alternative approaches, take a look at the answers to this related question.

Categories