public class J1_LAB08_1 {
public static void main(String[] args) {
int r1 = 5, c1 = 3;//rows and column for matrix a
int r2 = 3, c2 = 4;//rows and column for matrix b
int matrixA[][] = new int[5][3];//initialize matrix a
System.out.println("Matrix A");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {//create random single integer matrix
matrixA[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixA[i][j]);//print matrix a
}
System.out.println();
}
System.out.println();
System.out.println("Matrix B");
int matrixB[][] = new int[3][4];
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[i].length; j++) {//create random single integer matrix
matrixB[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixB[i][j]);//print matrix b
}
System.out.println();
}
System.out.println();
int[][] matrixC = multiplyMatrices(matrixA, matrixB, r1, c1, c2);//pass variables to multiply matrices function
printC(matrixC);//print matrix c
}
public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB, int r1, int c1, int c2){//multiply the 2 given matrices and return the product
int[][] matrixC = new int[r1][c2];//initialize the product matrix using row a and column 2 as its parameters
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];//multiply using textbook formula
}
}
}
return matrixC;
}
public static void printC(int[][] matrixC) {//print the matrix
System.out.println("A x B is: ");
for(int[] row : matrixC) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
is there any way to simplify my code for matrix multiplication?
the resulting matrix should be 3 x 5 after multiplication
any help would be greatly appreciated, thank you for your time and consideration.
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.
The program should multiply 2 matrices 4x1 and 1x4 and output the result to the console (matrix 4X4). But nothing displays. What's the problem?
public class Matrix {
public static void main(String[] args) {
int[][] matrixA = new int[4][1];
int[][] matrixB = new int[1][4];
int[][] matrixC = new int[4][4];
matrixA[0][0] = 1;
matrixA[1][0] = 2;
matrixA[2][0] = 3;
matrixA[3][0] = 4;
matrixB[0][0] = 4;
matrixB[0][1] = 3;
matrixB[0][2] = 2;
matrixB[0][3] = 1;
for (int i = 0; i < 4; i++) { // A rows
for (int j = 0; j < 4; j++) { // B columns
for (int k = 0; k < 1; k++) { // A columns
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
System.out.print(matrixC[i][j] + " ");
}
}
}
int j = 0;
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 1; k++)
System.out.print(matrixC[i][j] + " ");
System.out.println();
}
} //end main
} //end class
You introduced a variable j before your second set of for loops. Also, even if they're optional, I would highly recommend always including braces. And k < 4. Like,
for (int i = 0; i < 4; i++) {
for (int k = 0; k < 4; k++) {
System.out.print(matrixC[i][k] + " "); // not [i][j]
}
System.out.println();
}
or just use Arrays.deepToString(Object[]) like
System.out.println(Arrays.deepToString(matrixC));
Hope this helps:
public class Matrix {
public static void main(String[] args) {
int[][] matrixA = {{1}, {2}, {3}, {4}};
int[][] matrixB = {{4, 3, 2, 1}};
int[][] matrixC = new int[4][4];
for (int i = 0; i < 4; i++) { // A rows
for (int j = 0; j < 4; j++) { // B columns
for (int k = 0; k < 1; k++) { // A columns
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
System.out.print(matrixC[i][j] + " ");
}
}
System.out.println();
}
}
}
Output:
4 3 2 1
8 6 4 2
12 9 6 3
16 12 8 4
I have this assignment for my class where I have to create a Matrix Multiplication program. Here's the condition:
Implement two types of algorithms for multiplying two n × n matrices. Assume n is a power of 2:
The straight-forward O(n^3) matrix multiplication algorithm.
Strassen’s matrix multiplication algorithm.
Evaluate your different algorithms, and write a short report. Create test matrices for different values of n (4, 10, 20,100). Generate matrices using random numbers. Compute the running time of your algorithms. Your report should include the running times and conclusions.
Here's my code so far:
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
double[][] a = new double[rows][columns];
double[][] b = new double[columns][rows];
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(a);
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(b);
System.out.println();
Matrix productRegular = m1.multiply(m2);
}
}
And here's my other class:
import java.util.Random;
class Matrix
{
double[][] arrayA;
double[][] arrayB;
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
}
public double multiply(double[][] a, double[][] b)
{
double[][] c = new double[a.length][b[0].length];
System.out.println("Product of A and B is");
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < a[0].length; k++)
{
c[i][j] += a[i][k] * b[k][j];
System.out.println(c[i][j] + " | ");
}
}
System.out.println();
}
return c;
}
}
I know I have to pass an object/Matrix for the multiply method, but how would I do that? There are other concerns in my code, but I want to focus on passing objects right now.
Let's take a deep look to your code:
Why do you have two double[][] inside the Matrix class? A Matrix is just one bidimensional array. You should delete the arrayB
double[][] arrayA;
double[][] arrayB;
What's the point of the private constructor? For you, it is useless right now.
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
In the public constructor, you are printing a Matrix, but you are not saving anywhere.
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Anyway, I think it would be much better to make 2 constructors
public Matrix(double[][] array) //you just pass an array created outside the class
{
arrayA = array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][] array = new double [rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Why your multiply method have 2 parameters? As it is inside the class Matrix (that have a double[][]variable). You only need a parameter (I think it is better to your example to have a Matrix parameter instead of a double[][]parameter and return also a Matrix).
I don't like printing when you are creating or multiplying. It's much better to create a method to print the Matrix, and calling it when you want to print them.
So....the final code would be something like this:
Main
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(rows,columns);
m1.print();
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(columns, rows);
m2.print();
System.out.println();
System.out.println("Product of A and B is");
Matrix productRegular = m1.multiply(m2);
productRegular.print();
}
}
Matrix Class
import java.util.Random;
class Matrix
{
double[][] arrayA;
public Matrix(double[][] array) //Create matrix values
{
arrayA=array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][]array= new double[rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
}
}
arrayA=array;
}
public Matrix multiply(Matrix m)
{
double[][]b=m.arrayA;
double[][] c = new double[arrayA.length][b[0].length];
for(int i = 0; i < arrayA.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < arrayA[0].length; k++)
{
c[i][j] += arrayA[i][k] * b[k][j];
}
}
}
return new Matrix(c);
}
public void print(){
for(int i=0;i<arrayA.length;i++){
for(int j=0;j<arrayA[0].length;j++){
System.out.print(arrayA[i][j] + " | ");
}
System.out.println();
}
}
}
I have this example matrix:
[4,1,3]
[2,1,3]
[4,-1,6]
and i want to solve exuotions:
4x1+1x2+3x3=v
2x1+1x2+2x3=v
4x1-1x2+6x3=v
x1+x2+x3=1
it will be: 4x1+1x2+3x3 = 2x1+1x2+2x3 = 4x1-1x2+6x3
-2x1+x2-5x3 =0
and I use the code:
import java.util.*;
public class GaussianElimination {
// This is the problem we solved in class
private static double[][] problem1 = {
// x = 1, y = 2, z = 3
{ 1, 2, 3, 14 }, // 1x + 2y + 3z = 14
{ 1, -1, 1, 2 }, // 1x - 1y + 1z = 2
{ 4, -2, 1, 3 } // 4x - 2y + 1z = 3
};
public static void solve(double[][] c, int row) {
int rows = c.length;
int cols = rows + 1;
// 1. set c[row][row] equal to 1
double factor = c[row][row];
for (int col=0; col<cols; col++)
c[row][col] /= factor;
// 2. set c[row][row2] equal to 0
for (int row2=0; row2<rows; row2++)
if (row2 != row) {
factor = -c[row2][row];
for (int col=0; col<cols; col++)
c[row2][col] += factor * c[row][col];
}
}
public static void solve(double[][] c) {
int rows = c.length;
for (int row=0; row<rows; row++)
solve(c,row);
}
public static void print(double[][] c) {
int rows = c.length;
int cols = rows + 1;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++)
System.out.printf("%5.1f ",c[row][col]);
System.out.println();
}
System.out.println();
}
public static void printSolution(double[][] c) {
int rows = c.length, cols = rows + 1;
char variable = (char)((rows > 3) ? ('z' - (rows-1)) : 'x');
System.out.println("Solution:\n");
for (int row=0; row<rows; row++)
System.out.printf(" %c = %1.1f\n",(char)variable++,c[row][cols-1]);
System.out.println();
}
public static void doProblem(double[][] problem, String description) {
System.out.printf("******* %s ********\n",description);
System.out.println("Original Equations:");
print(problem);
solve(problem);
System.out.println("Solved (reduced row echelon form):");
print(problem);
printSolution(problem);
}
public static void main(String[] args) {
doProblem(problem1,"Problem 1 (from class)");
}
}
How do I set the matrix in private static double[][] problem1 so that I get x1,x2,x3?
I don't really understand your question or problem. However I see some bugs in the row reduction echelon form solving method. I recently wrote this method as well. Mine works. Since I don't suspect this to be a Java homework assignment but rather an interest in programming mathematical algorithms, I will just throw in my code. I recommend taking a look at how the rref method is actually defined in the world of maths.
The bug I spotted is that the factor you use is wrong. Take a look at my code (note that it doesn't put zero rows to the bottom of the matrix):
public static double[][] rref(double[][] mat)
{
double[][] rref = new double[mat.length][mat[0].length];
/* Copy matrix */
for (int r = 0; r < rref.length; ++r)
{
for (int c = 0; c < rref[r].length; ++c)
{
rref[r][c] = mat[r][c];
}
}
for (int p = 0; p < rref.length; ++p)
{
/* Make this pivot 1 */
double pv = rref[p][p];
if (pv != 0)
{
double pvInv = 1.0 / pv;
for (int i = 0; i < rref[p].length; ++i)
{
rref[p][i] *= pvInv;
}
}
/* Make other rows zero */
for (int r = 0; r < rref.length; ++r)
{
if (r != p)
{
double f = rref[r][p];
for (int i = 0; i < rref[r].length; ++i)
{
rref[r][i] -= f * rref[p][i];
}
}
}
}
return rref;
}
The following code adapted from Rosettacode.org takes into account moving rows up/down as well:
static public void rref(double [][] m)
{
int lead = 0;
int rowCount = m.length;
int colCount = m[0].length;
int i;
boolean quit = false;
for(int row = 0; row < rowCount && !quit; row++)
{
print(m);
println();
if(colCount <= lead)
{
quit = true;
break;
}
i=row;
while(!quit && m[i][lead] == 0)
{
i++;
if(rowCount == i)
{
i=row;
lead++;
if(colCount == lead)
{
quit = true;
break;
}
}
}
if(!quit)
{
swapRows(m, i, row);
if(m[row][lead] != 0)
multiplyRow(m, row, 1.0f / m[row][lead]);
for(i = 0; i < rowCount; i++)
{
if(i != row)
subtractRows(m, m[i][lead], row, i);
}
}
}
}
// swaps two rows
static void swapRows(double [][] m, int row1, int row2)
{
double [] swap = new double[m[0].length];
for(int c1 = 0; c1 < m[0].length; c1++)
swap[c1] = m[row1][c1];
for(int c1 = 0; c1 < m[0].length; c1++)
{
m[row1][c1] = m[row2][c1];
m[row2][c1] = swap[c1];
}
}
static void multiplyRow(double [][] m, int row, double scalar)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[row][c1] *= scalar;
}
static void subtractRows(double [][] m, double scalar, int subtract_scalar_times_this_row, int from_this_row)
{
for(int c1 = 0; c1 < m[0].length; c1++)
m[from_this_row][c1] -= scalar * m[subtract_scalar_times_this_row][c1];
}
static public void print(double [][] matrix)
{
for(int c1 = 0; c1 < matrix.length; c1++)
{
System.out.print("[ ");
for(int c2 = 0; c2 < matrix[0].length-1; c2++)
System.out.print(matrix[c1][c2] + ", ");
System.out.println(matrix[c1][matrix[c1].length-1] + " ]");
}
}
static public void println()
{
System.out.println();
}
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.