Matrix substraction differences in Python and Java - java

I have a problem with matrix substraction in Python and Java. I have followed the same steps in both programming languages but outputs are different.
import numpy as np
array1 = [[1,3], [5,6],[7,8]]
array1 = np.transpose(array1)
array2 = [[1,0,1]]
array3 = np.subtract(array2,array1)
print(array3)
which output is matrix like this:
[[ 0 -5 -6]
[-2 -6 -7]]
This works fine and in the way i need. But i need this output in Java. So i have tried following snippet of code:
double [][] array1 = new double[][]{
{1,2},
{3,4},
{5,6}
};
double [][] array2 = new double[][]{
{1,0,1}
};
array1 = np.T(array1);
double [][] vysl = np.subtract(array2, array1);
where
public static double[][] subtract(double[][] a, double[][] b) {
int m = a.length;
int n = a[0].length;
double[][] c = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j] - b[i][j];
}
}
return c;
}
public static double[][] T(double[][] a) {
int m = a.length;
int n = a[0].length;
double[][] b = new double[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
b[j][i] = a[i][j];
}
}
return b;
}
But the result is different matrix :
for (int i = 0; i < vysl.length; i++)
{
for (int y = 0; y < vysl[0].length; y++)
System.out.print(vysl[i][y] + " ");
System.out.println("");
}
0.0 -3.0 -4.0
I have displayed the matrix with this 2D cycle. This matrix has only 1 row with 3 columns, but the preceding matrix from pythom had 2 rows a 3 columns. Can you please tell me what I am doing wrong a the way I can get the matrix with 2 rows and 3 columns in Java? How can I implement broadcasting rule in Java?

I could see issue in your code...for your use case following code gives expected output
public static void main(String[] args) {
double[][] array1 = new double[][] { { 1, 3 }, { 5, 6 }, { 7, 8 } };
double[][] array2 = new double[][] { { 1, 0, 1 } };
array1 = np(array1);
double[][] vysl = subtract(array2, array1);
System.out.println("complete");
}
public static double[][] np(double[][] a) {
int x = a.length;
int y = a[0].length;
double[][] c = new double[y][x];
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
c[i][j] = a[j][i];
}
}
return c;
}
public static double[][] subtract(double[][] a, double[][] b) {
int m = b.length;
int n = b[0].length;
double[][] c = new double[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = a[0][j] - b[i][j];
}
}
return c;
}

Related

Value in the method changes which I didn't expect to happen

so I'm trying to make a program that rotates a cube shaped grid 90 degree to the right.
The problem I encountered is that temp values (temp1, temp2, temp3, temp4) that I declared in the method keep changes during the process of method.
Assume there is a cube grid,
1 2 3
4 5 6
7 8 9
as I declared
int[] temp1 = grid[0]; in the method
temp1 should be fixed as {1, 2, 3}.
However, when this part of code executes,
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
temp1's value changes as {7, 4, 1} which I didn't not expect
It is really confusing because temp value usually don't change.
Can anyone give me advice to fix this issue?
import java.util.Scanner;
public class a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numLine = Integer.parseInt(input.nextLine());
int[][] grid = new int[numLine][numLine];
String[] lines = null;
for (int i = 0; i < numLine; i++)
{
lines = input.nextLine().split(" ");
for (int j = 0; j < numLine; j++)
{
grid[i][j] = Integer.parseInt(lines[j]);
}
}
rotate(grid);
for (int[] i : grid)
{
for (int j : i)
{
System.out.print(j + " ");
}
System.out.println("");
}
input.close();
}
public static void rotate(int[][] grid)
{
//row 0
int[] temp1 = grid[0];
//column 0
int[] temp2 = new int[grid[0].length];
int c = 0;
for (int i = grid[0].length-1; i >= 0; i--)
{
temp2[c] = grid[i][0];
c++;
}
c = 0;
//row last
int[] temp3 = grid[grid[0].length-1];
//column last
int[] temp4 = new int[grid[0].length];
for (int i = grid[0].length-1; i >= 0; i--)
{
temp4[c] = grid[i][grid[0].length-1];
c++;
}
c = 0;
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
//column last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][grid[0].length-1] = temp1[i];
}
//row last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[grid[0].length-1][i] = temp4[i];
}
//column 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][0] = temp3[i];
}
}
}

Finding the Minor Matrix

I have a Matrix class that has the following method
private Matrix matrixMinors()
{
double[][] matrixM = new double[matrix.length][matrix.length];
for(int i = 0; i < matrixM.length; i++)
for(int j = 0; j < matrixM.length; j++)
{
double[][] newone = new double[matrixM.length - 1][matrixM.length - 1];
for(int k = 0; k < newone.length; k++)
for(int h = 0; h < newone[0].length; h++)
if(k == i)
;
else if(h == j)
;
else
newone[k][h] = matrix[k][h];
test(newone, "little matrix"); //this just prints the matrix for debugging purposes
matrixM[i][j] = determinant(newone, newone.length);
}
test(matrixM, "minor matrix"); //this just prints the matrix for debugging purposes
return new Matrix(matrixM);
}
When printed the minor matrix has all zeros, any suggestions as to how to fix this.
Update:
My determinant method keeps printing only zeros, but I'm not sure if that's just because the data I'm giving it makes a zero determinant or my code is faulty.
private double determinant(double[][] mat, int size)
{
double det = 0;
if(size == 1)
det = mat[0][0];
else if (size == 2)
det = mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1];
else
{
for(int j1 = 0; j1 < size; j1++)
{
double[][] m = new double[size-1][];
for(int k = 0; k < (size-1); k++)
m[k] = new double[size-1];
for(int i = 1; i < size; i++)
{
int j2 = 0;
for(int j = 0; j < size; j++)
{
if(j == j1)
continue;
m[i-1][j2] = mat[i][j];
j2++;
}
}
det += Math.pow(-1.0, 1.0 + j1 + 1.0) * mat[0][j1] * determinant(m, size - 1);
}
}
return det;
}
My first advice would be to replace the ugly if-else:
This one:
if(k == i)
;
else if(h == j)
;
else
newone[k][h] = matrix[k][h];
With:
if(k!=i && h!=j) {
System.out.println("test: "+matrix[k][h]);//to see if it enters here
newone[k][h] = matrix[k][h];
}
If the test is not printed, then the logic is wrong.
My second advice:
Write a UnitTest for your determinant method or at least check what it returns (a System.out could help). If it always returns 0, then the minor matrix is, of course, all zeros.
Edit:
You do not need to pass the size to determinant. You can simply use:
private double determinant(double[][] mat)
{
int size = mat.length;
I tested that method with a few matixes like this:
final double[][] mat = new double[][] { { 1, 0, 1 }, { 0, 1, 0 }, { 2, 0, 1 } };
final double det = determinant(mat, 3);
System.out.println("det: " + det);
The result was as expected.
Since newone is not as expected, here a Test class you can use:
public class TestMatrix
{
private static final double delta = 0.0001;
#Test
public void testDeterminant()
{
final double[][] mat = new double[][] { { 1.5, 2.7, 3.8 }, { -4.1, 5.4, -6.6 }, { 7.1, 8000, 9000 } };
final double det = Matrix.determinant(mat, 3);
assertEquals(126817.786, det, delta);
}
// TODO add other tests!
#Test
public void testNewOne() throws Exception
{
final double[][] matrix = { { 3, 0, 2 }, { 2, 0, -2 }, { 0, 1, 1 } };
final double[][] newOne = Matrix.newOne(matrix, 0, 0);
assertMatrix(new double[][] { { 0, -2 }, { 1, 1 } }, newOne);
}
private void assertMatrix(final double[][] ds, final double[][] newOne)
{
assertEquals(ds.length, newOne.length);
for (int i = 0; i < ds.length; i++)
{
assertEquals(ds[i].length, newOne[i].length);
for (int j = 0; j < ds[i].length; j++)
{
assertEquals(ds[i][j], newOne[i][j], delta);
}
}
}
}
I wrote a newOne method like this:
public static double[][] newOne(final double[][] matrix, final int i, final int j)
{
final double[][] newone = new double[matrix.length - 1][matrix.length - 1];
for(int k = 0; k < newone.length; k++)
{
for(int h = 0; h < newone[0].length; h++)
if (k != i && h != j)
{
newone[k][h] = matrix[k][h];
}
}
return newone;
}
Your matrixMinor would then be:
//...
for(int i = 0; i < matrixM.length; i++)
for(int j = 0; j < matrixM.length; j++)
{
double[][] newone = newOne(matrixM, i, j);
test(newone, "little matrix");
matrixM[i][j]=determinant(newone, newone.length);
}
//...
Then just change the method newOne until the UnitTest pass (a few more Tests wouldn't hurt, I just wrote one to show you how it can be done).

Matrix multiplication using arrays

I'm trying to make a simple matrix multiplication method using multidimensional arrays ([2][2]). I'm kinda new at this, and I just can't find what it is I'm doing wrong. I'd really appreciate any help in telling me what it is. I'd rather not use libraries or anything like that, I'm mostly doing this to learn how it works. Thank you so much in advance.
I'm declaring my arays in the main method as follows:
Double[][] A={{4.00,3.00},{2.00,1.00}};
Double[][] B={{-0.500,1.500},{1.000,-2.0000}};
A*B should return the identity matrix. It doesn't.
public static Double[][] multiplicar(Double[][] A, Double[][] B){
//the method runs and returns a matrix of the correct dimensions
//(I actually changed the .length function to a specific value to eliminate
//it as a possible issue), but not the correct values
Double[][] C= new Double[2][2];
int i,j;
////I fill the matrix with zeroes, if I don't do this it gives me an error
for(i=0;i<2;i++) {
for(j=0;j<2;j++){
C[i][j]=0.00000;
}
}
///this is where I'm supposed to perform the adding of every element in
//a row of A multiplied by the corresponding element in the
//corresponding column of B, for all columns in B and all rows in A
for(i=0;i<2;i++){
for(j=0;j<2;j++)
C[i][j]+=(A[i][j]*B[j][i]);
}
return C;
}
You can try this code:
public class MyMatrix {
Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };
Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };
public static Double[][] multiplicar(Double[][] A, Double[][] B) {
int aRows = A.length;
int aColumns = A[0].length;
int bRows = B.length;
int bColumns = B[0].length;
if (aColumns != bRows) {
throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
}
Double[][] C = new Double[aRows][bColumns];
for (int i = 0; i < aRows; i++) {
for (int j = 0; j < bColumns; j++) {
C[i][j] = 0.00000;
}
}
for (int i = 0; i < aRows; i++) { // aRow
for (int j = 0; j < bColumns; j++) { // bColumn
for (int k = 0; k < aColumns; k++) { // aColumn
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
public static void main(String[] args) {
MyMatrix matrix = new MyMatrix();
Double[][] result = multiplicar(matrix.A, matrix.B);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
System.out.print(result[i][j] + " ");
System.out.println();
}
}
}
Java. Matrix multiplication.
Tested with matrices of different size.
public class Matrix {
/**
* Matrix multiplication method.
* #param m1 Multiplicand
* #param m2 Multiplier
* #return Product
*/
public static double[][] multiplyByMatrix(double[][] m1, double[][] m2) {
int m1ColLength = m1[0].length; // m1 columns length
int m2RowLength = m2.length; // m2 rows length
if(m1ColLength != m2RowLength) return null; // matrix multiplication is not possible
int mRRowLength = m1.length; // m result rows length
int mRColLength = m2[0].length; // m result columns length
double[][] mResult = new double[mRRowLength][mRColLength];
for(int i = 0; i < mRRowLength; i++) { // rows from m1
for(int j = 0; j < mRColLength; j++) { // columns from m2
for(int k = 0; k < m1ColLength; k++) { // columns from m1
mResult[i][j] += m1[i][k] * m2[k][j];
}
}
}
return mResult;
}
public static String toString(double[][] m) {
String result = "";
for(int i = 0; i < m.length; i++) {
for(int j = 0; j < m[i].length; j++) {
result += String.format("%11.2f", m[i][j]);
}
result += "\n";
}
return result;
}
public static void main(String[] args) {
// #1
double[][] multiplicand = new double[][] {
{3, -1, 2},
{2, 0, 1},
{1, 2, 1}
};
double[][] multiplier = new double[][] {
{2, -1, 1},
{0, -2, 3},
{3, 0, 1}
};
System.out.println("#1\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
// #2
multiplicand = new double[][] {
{1, 2, 0},
{-1, 3, 1},
{2, -2, 1}
};
multiplier = new double[][] {
{2},
{-1},
{1}
};
System.out.println("#2\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
// #3
multiplicand = new double[][] {
{1, 2, -1},
{0, 1, 0}
};
multiplier = new double[][] {
{1, 1, 0, 0},
{0, 2, 1, 1},
{1, 1, 2, 2}
};
System.out.println("#3\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
}
}
Output:
#1
12.00 -1.00 2.00
7.00 -2.00 3.00
5.00 -5.00 8.00
#2
0.00
-4.00
7.00
#3
0.00 4.00 0.00 0.00
0.00 2.00 1.00 1.00
static int b[][]={{21,21},{22,22}};
static int a[][] ={{1,1},{2,2}};
public static void mul(){
int c[][] = new int[2][2];
for(int i=0;i<b.length;i++){
for(int j=0;j<b.length;j++){
c[i][j] =0;
}
}
for(int i=0;i<a.length;i++){
for(int j=0;j<b.length;j++){
for(int k=0;k<b.length;k++){
c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
}
}
}
for(int i=0;i<c.length;i++){
for(int j=0;j<c.length;j++){
System.out.print(c[i][j]);
}
System.out.println("\n");
}
}
Try this,
public static Double[][] multiplicar(Double A[][],Double B[][]){
Double[][] C= new Double[2][2];
int i,j,k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
C[i][j] = 0.00000;
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for (k=0;k<2;k++){
C[i][j]+=(A[i][k]*B[k][j]);
}
}
}
return C;
}
try this,it may help you
import java.util.Scanner;
public class MulTwoArray {
public static void main(String[] args) {
int i, j, k;
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array a");
int rowa = sc.nextInt();
int cola = sc.nextInt();
System.out.println("Enter size of array b");
int rowb = sc.nextInt();
int colb = sc.nextInt();
//read and b
System.out.println("Enter elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
a[i][j] = sc.nextInt();
}
System.out.println();
}
System.out.println("Enter elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
b[i][j] = sc.nextInt();
}
System.out.println("\n");
}
//print a and b
System.out.println("the elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
System.out.print(a[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("the elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(b[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
//multiply a and b
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
c[i][j] = 0;
for (k = 0; k < cola; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//print multi result
System.out.println("result of multiplication of array a and b is ");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
}
}
The method mults is a procedure(Pascal) or subroutine(Fortran)
The method multMatrix is a function(Pascal,Fortran)
import java.util.*;
public class MatmultE
{
private static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
double[][] A={{4.00,3.00},{2.00,1.00}};
double[][] B={{-0.500,1.500},{1.000,-2.0000}};
double[][] C=multMatrix(A,B);
printMatrix(A);
printMatrix(B);
printMatrix(C);
double a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
double b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
double[][] c=multMatrix(a,b);
printMatrix(a);
printMatrix(b);
printMatrix(c);
double[][] a1 = readMatrix();
double[][] b1 = readMatrix();
double[][] c1 = new double[a1.length][b1[0].length];
mults(a1,b1,c1,a1.length,a1[0].length,b1.length,b1[0].length);
printMatrix(c1);
printMatrixE(c1);
}
public static double[][] readMatrix() {
int rows = sc.nextInt();
int cols = sc.nextInt();
double[][] result = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = sc.nextDouble();
}
}
return result;
}
public static void printMatrix(double[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%8.3f " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void printMatrixE(double[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%9.2e " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static double[][] multMatrix(double a[][], double b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new double[0][0];
if(a[0].length != b.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = b[0].length;
double ans[][] = new double[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
ans[i][j]=0;
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
}
public static void mults(double a[][], double b[][], double c[][], int r1,
int c1, int r2, int c2){
for(int i = 0;i < r1;i++){
for(int j = 0;j < c2;j++){
c[i][j]=0;
for(int k = 0;k < c1;k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
}
where as input matrix you can enter
inE.txt
4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.0 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
in unix like cmmd line execute the command:
$ java MatmultE < inE.txt > outE.txt
and you get the output
outC.txt
Matrix[2][2]
4.000 3.000
2.000 1.000
Matrix[2][2]
-0.500 1.500
1.000 -2.000
Matrix[2][2]
1.000 0.000
0.000 1.000
Matrix[3][4]
1.000 2.000 -2.000 0.000
-3.000 4.000 7.000 2.000
6.000 0.000 3.000 1.000
Matrix[4][2]
-1.000 3.000
0.000 9.000
1.000 -11.000
4.000 -5.000
Matrix[3][2]
-3.000 43.000
18.000 -60.000
1.000 -20.000
Matrix[4][3]
-7.000 15.000 3.000
-36.000 70.000 20.000
-105.000 189.000 57.000
-256.000 420.000 96.000
Matrix[4][3]
-7.00e+00 1.50e+01 3.00e+00
-3.60e+01 7.00e+01 2.00e+01
-1.05e+02 1.89e+02 5.70e+01
-2.56e+02 4.20e+02 9.60e+01
My code is super easy and works for any order of matrix
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Enter No. of rows in matrix 1 : ");
int arows = sc.nextInt();
System.out.println(" Enter No. of columns in matrix 1 : ");
int acols = sc.nextInt();
System.out.println(" Enter No. of rows in matrix 2 : ");
int brows = sc.nextInt();
System.out.println(" Enter No. of columns in matrix 2 : ");
int bcols = sc.nextInt();
if (acols == brows) {
System.out.println(" Enter elements of matrix 1 ");
int a[][] = new int[arows][acols];
int b[][] = new int[brows][bcols];
for (int i = 0; i < arows; i++) {
for (int j = 0; j < acols; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println(" Enter elements of matrix 2 ");
for (int i = 0; i < brows; i++) {
for (int j = 0; j < bcols; j++) {
b[i][j] = sc.nextInt();
}
}
System.out.println(" The Multiplied matrix is : ");
int sum = 0;
int c[][] = new int[arows][bcols];
for (int i = 0; i < arows; i++) {
for (int j = 0; j < bcols; j++) {
for (int k = 0; k < brows; k++) {
sum = sum + a[i][k] * b[k][j];
c[i][j] = sum;
}
System.out.print(c[i][j] + " ");
sum = 0;
}
System.out.println();
}
} else {
System.out.println("Order of matrix in invalid");
}
}
multiply 4x4 Matrixes
float[] mul(float[] l, float[] r) {
float[] res = new float[16];
for (int i = 0; i < 16; i++) {
int y = i / 4;
int x = i % 4;
res[i] = l[x] * r[y] +
l[x + 4] * r[y + 4] +
l[x + 8] * r[y + 8] +
l[x + 12] * r[y + 12];
}
return res;
}
import java.util.*;
public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C = new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B.length; j++) {
B[i][j] = s.nextInt();
}
}
if (Cola == Rowb) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
C[i][j] = 0;
for (int k = 0; k < B.length; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
} else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
System.out.print(A[i][j] + "\t");
}
System.out.println();
}
*/
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
System.out.print(C[i][j] + "\t");
}
System.out.println();
}
}
}
#include <stdio.h>
int main()
{
int row = 2;
int col = 3;
int a[row][col];
int count = 1;
printf("Array A \n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
a[i][j] = count;
count++;
printf(" %d ", a[i][j]);
}
printf("\n");
}
int b[col][row];
printf("\nArray B \n");
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
b[i][j] = count;
count++;
printf(" %d ", b[i][j]);
}
printf("\n");
}
printf("\n A * B \n");
int c[row][col];
int mul = 1, plus = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < row; j++)
{
plus = 0;
for (int k = 0; k < col; k++)
{
mul = a[i][k] * b[k][j];
plus += mul;
}
c[i][j] = plus;
printf(" %d ", c[i][j]);
}
printf("\n");
}
}

How to reference sub-matrices within a matrix

I have an nxn matrix A where n is a power of 2. The matrix A is divided into 4 equal sized sub-matrices. How can I reference matrices the sub-matrices A11, A12, A21 and A22 in java? I am attempting a divide and conquer matrix multiplication algorithm (Strassen)
A11 | A12
A --> ---------
A21 | A22
EDIT: The matrix is stored as integer array: int[][].
Well, if i and j are your indices, then A11 is obtained for i = 0..(n/2)-1, j = 0..(n/2)-1.
Then, A12 is for i = 0..(n/2)-1 and j = n/2..n-1 and so on.
To 'reference' them, you just need an "i_min, i_max, j_min, j_max" and instead of running indices from 0 to n-1, run them from min to max.
This is an implementation of the Strassen algorithm for matrix multiplication
import java.io.*;
public class MatrixMultiplication {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public MatrixMultiplication() throws IOException {
int n;
int[][] a, b;
System.out.print("Enter the number for rows/colums: ");
n = Integer.parseInt(br.readLine());
a = new int[n][n];
b = new int[n][n];
System.out.print("\n\n\nEnter the values for the first matrix:\n\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print("Enter the value for cell("+(i+1)+","+(j+1)+"): ");
a[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.print("\n\n\nEnter the values for the second matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print("Enter the value for cell ("+(i+1)+","+(j+1)+"): ");
b[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.print("\n\nMatrix multiplication using standard method:\n");
print(multiplyWithStandard(a, b));
System.out.print("\n\nMatrix multiplication using Strassen method:\n");
print(multiplyWithStandard(a, b));
}
public int[][] multiplyWithStandard(int[][] a, int[][] b) {
int n = a.length;
int[][] c = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return c;
}
public int[][] multiplyWithStrassen(int [][] A, int [][] B) {
int n = A.length;
int [][] result = new int[n][n];
if (n == 1) {
result[0][0] = A[0][0] * B[0][0];
} else if ((n%2 != 0 ) && (n != 1)) {
int[][] a1, b1, c1;
int n1 = n+1;
a1 = new int[n1][n1];
b1 = new int[n1][n1];
c1 = new int[n1][n1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a1[i][j] = A[i][j];
b1[i][j] = B[i][j];
}
}
c1 = multiplyWithStrassen(a1, b1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = c1[i][j];
}
}
} else {
int [][] A11 = new int[n/2][n/2];
int [][] A12 = new int[n/2][n/2];
int [][] A21 = new int[n/2][n/2];
int [][] A22 = new int[n/2][n/2];
int [][] B11 = new int[n/2][n/2];
int [][] B12 = new int[n/2][n/2];
int [][] B21 = new int[n/2][n/2];
int [][] B22 = new int[n/2][n/2];
divideArray(A, A11, 0 , 0);
divideArray(A, A12, 0 , n/2);
divideArray(A, A21, n/2, 0);
divideArray(A, A22, n/2, n/2);
divideArray(B, B11, 0 , 0);
divideArray(B, B12, 0 , n/2);
divideArray(B, B21, n/2, 0);
divideArray(B, B22, n/2, n/2);
int [][] M1 = multiplyWithStrassen(add(A11, A22), add(B11, B22));
int [][] M2 = multiplyWithStrassen(add(A21, A22), B11);
int [][] M3 = multiplyWithStrassen(A11, subtract(B12, B22));
int [][] M4 = multiplyWithStrassen(A22, subtract(B21, B11));
int [][] M5 = multiplyWithStrassen(add(A11, A12), B22);
int [][] M6 = multiplyWithStrassen(subtract(A21, A11), add(B11, B12));
int [][] M7 = multiplyWithStrassen(subtract(A12, A22), add(B21, B22));
int [][] C11 = add(subtract(add(M1, M4), M5), M7);
int [][] C12 = add(M3, M5);
int [][] C21 = add(M2, M4);
int [][] C22 = add(subtract(add(M1, M3), M2), M6);
copyArray(C11, result, 0 , 0);
copyArray(C12, result, 0 , n/2);
copyArray(C21, result, n/2, 0);
copyArray(C22, result, n/2, n/2);
}
return result;
}
public int[][] add(int [][] A, int [][] B) {
int n = A.length;
int [][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
result[i][j] = A[i][j] + B[i][j];
}
return result;
}
public int[][] subtract(int [][] A, int [][] B) {
int n = A.length;
int [][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = A[i][j] - B[i][j];
}
}
return result;
}
private void divideArray(int[][] parent, int[][] child, int iB, int jB) {
for (int i1 = 0, i2 = iB; i1 < child.length; i1++, i2++) {
for (int j1 = 0, j2 = jB; j1 < child.length; j1++, j2++) {
child[i1][j1] = parent[i2][j2];
}
}
}
private void copyArray(int[][] child, int[][] parent, int iB, int jB) {
for(int i1 = 0, i2 = iB; i1 < child.length; i1++, i2++) {
for(int j1 = 0, j2 = jB; j1 < child.length; j1++, j2++) {
parent[i2][j2] = child[i1][j1];
}
}
}
public void print(int [][] array) {
int n = array.length;
System.out.println();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(array[i][j] + "\t");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) throws IOException {
new MatrixMultiplication();
}
}
I think you have to decide whether to copy the contents of each submatrix each time or to do arithmetic on the addressing. Your questions implies that your submatrices are contiguous rather than split (as in calculating detrminants with minors and cofactors - http://mathworld.wolfram.com/Determinant.html). Since you haven't given an indication of why you wish to do this, what performance hits you have already encountered, and whether there is recursion to smaller matrices I think that only you can decide on the balance between the simplicity of copying or the complexity of recursive addressing. But I would expect there to be libraries already and I would check http://commons.apache.org/math/.

How Can I Display a N x N Matrix of Random Numbers in Java?

I'm trying to create a matrix of random double numbers. The matrix must be of size n x n and all numbers must be between 1 and 100. I've been trying to sort it out for ages now and I know it must be something so simple (as it usually is).
Here is my code:
public static void main(String[] args) {
PrintRandomGraph(RandomArray(4));
}
private static double[] RandomArray(int n) {
double[] randomArray = new double[n];
double[][] randomMatrix = new double [n][n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
Integer r = rand.nextInt()% 100;
randomArray[i] = Math.abs(r);
for (int j = 0; j < n; j++) {
Arrays.fill(randomMatrix, i, i+1, randomArray);
}
}
return randomArray;
}
private static void PrintRandomGraph(double[] inputArray) {
int n = inputArray.length;
double[] showArray = new double[n];
double[][] showMatrix = new double [n][n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
double r = inputArray[i];
showArray[i] = r;
Arrays.fill(showMatrix, i, i+1, showArray);
}
}
System.out.println(Arrays.deepToString(showMatrix));
}
When I run the code I get a random array repeated n times like :
[[63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0]]
I think I need to go back to the top of the for loop and add the new array...? Please help =(
Any help is much appreciated. Thank you.
Did you try something like this:
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][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;
}
to Print the graph:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(array[i][j]);
}
}
}
To Print Graph with Square brackets:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" [ ");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]);
}
//Put println instead of print here to have each row in a new line
System.out.print(" ]");
}
}
Also, this seems a lot like homework, if it is, please tag it like so :)
Hi all this provides the answer I was looking for
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){
//PrintRandomGraph(RandomArray(5));
System.out.println(Arrays.deepToString(RandomArray(5)));
}

Categories

Resources