So in my code, I am supposed to add together two matrix objects using this notation m1.add(m2) where m1 is and m2 are objects and add is the method being invoked. This is what my code looks like right now. I have one constructor that generates a matrix when an object in the main method is created. Whenever I try to run the program in the main method, it gives me an error. I have to essentially take a matrix object and add it with another matrix object. Note the matrix object is created and run through the constructor first.
import java.util.Arrays;
public class matrix {
int row;
int column;
static int[][] matrix;
matrix(int row, int column) {
this.row = row;
this.column = column;
if (row < 1 || column < 1) {
this.row = 1;
this.column = 1;
}
if (row > 5 || column > 5) {
this.row = 5;
this.column = 5;
}
this.matrix = new int[this.row][this.column];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = (int) (Math.random() * 21) - 10;
}
}
toString(matrix);
}
public static void toString(int[][] matrix2) {
// for loop and prints each indexed variable using the system.out.print
// method.
for (int i = 0; i < matrix2.length; i++) {
System.out.print("\n");
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf("%5d", matrix2[i][j]);
}
System.out.print("\n");
}
}
public static void add( int[][] B)
{
int[][]sumMatrix = new int[matrix.length][B[0].length];
for(int i =0; i < matrix.length; i++)
{
for(int j=0; j < matrix[i].length;j++)
{
sumMatrix[i][j] = matrix[i][j] + B[i][j];
}
}
toString(sumMatrix);
}
Related
I want to calculoate the determinant of a given NxN Matrix using the Laplace-Method. I already tried differnt approaches which always return a 0.
The class I used:
package Matrix;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Matrix
{
double[][] array;
public static void init(Matrix a,int row , int column)
{
a.array = new double [row] [column];
for (int i = 0; i < row; i++)
{
for(int k = 0; k < column; k++)
{
a.array[i][k] = 0;
}
}
}
public static int getNRows(Matrix a)
{
return a.array.length;
}
public static int getNColumns(Matrix a)
{
return a.array[0].length;
}
public static void print(Matrix a)
{
for(int i = 0; i < getNRows(a);i++ )
{
for (int k = 0; k < getNColumns(a); k++)
{
System.out.print(a.array[i][k] + "\t");
}
System.out.println();
}
}
public static double det(Matrix a)
{
double det = 0;
det = a.array[0][0] * a.array[1][1] * a.array[2][2] + a.array[1][0] * a.array[2][1] * a.array[0][2] + a.array[2][0] * a.array[0][1] * a.array[1][2] - a.array[2][0] * a.array[1][1] * a.array[0][2] - a.array[1][0] * a.array[0][1] * a.array[2][2] - a.array[0][0] * a.array[2][1] * a.array[1][2];
return det;
public static Matrix transpose(Matrix a)
{
Matrix transposed = new Matrix();
Matrix.init(transposed, getNRows(a), getNColumns(a));
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
transposed.array[j][i] = a.array[i][j];
}
}
return transposed;
}
public static Matrix subMatrix(Matrix a, int exclRow, int exclCol)
{
Matrix subMatrix = new Matrix();
Matrix.init(subMatrix, getNRows(a) - 1, getNColumns(a) - 1);
for(int i = 0; i < getNRows(a) - 1; i++)
{
for(int j = 0; j < getNColumns(a) - 1; j++)
{
if(i != exclRow && j != exclCol)
{
subMatrix.array[i][j] = a.array[i][j];
}
}
}
return subMatrix;
}
public static Matrix loadMatrix(String filename) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
Matrix result = new Matrix();
int row = 0;
int col = 0;
String[] line = sc.nextLine().trim().split("\t");
row = Integer.parseInt(line[0]);
col = Integer.parseInt(line[1]);
init(result, row, col);
int currentRow = 0;
while(sc.hasNextLine())
{
String[] line2 =sc.nextLine().trim().split("\t");
for(int i = 0; i < col; i++)
{
result.array[currentRow][i] = Double.parseDouble(line2[i]);
}
currentRow++;
}
return result;
}
/*public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
double value = 1;
if(colOfA != rowOfA)
{
return 0;
}
if(colOfA == 1 && rowOfA == 1)
{
return a.array[0][0];
}
else
{
for(int row = 0; row < rowOfA; row++)
{
value += Math.pow(-1, row) * a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}*/
public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
if(colOfA != rowOfA)
{
return 0;
}
if(rowOfA <= 3)
{
return det(a);
}
double value = 0;
for(int row = 0; row < rowOfA; row++)
{
if(row % 2 == 0)
{
value += a.array[row][0] * detN(subMatrix(a, row, 0));
}
else
{
value -= a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}
public static Matrix adjointN(Matrix a)
{
int rowOfA = getNRows(a);
int colOfA = getNColumns(a);
Matrix ret = new Matrix();
Matrix.init(ret, rowOfA, colOfA);
for(int row = 0; row < rowOfA; row++)
{
for(int col = 0; col < colOfA; col++)
{
ret.array[row][col] = detN(subMatrix(a, row, col));
}
ret = transpose(ret);
return ret;
}
return ret;
}
public static Matrix inverseN(Matrix a)
{
Matrix inverse = new Matrix();
Matrix.init(inverse, getNRows(a), getNColumns(a));
double pre = 1/detN(a);
inverse = adjointN(a);
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
inverse.array[j][i] = inverse.array[i][j] * pre;
}
}
return inverse;
}
}
I have two versions for detN, which both yield the same result.
This isn't the entire class, because there are some functions that don't belong to this particular question
Here is an approach you could consider(the code is not fully debugged so take with a grain of salt). Finding the determinant is a recursive concept since you are always finding the determinant of a smaller matrix to get the final answer.
//Recursive base function
public static double det(int[][] matrix) {
if(matrix.length == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]));
double determinant = 0;
int mlength = matrix.length - 1;
int[][] newM = new int[mlength][mlength];
for(int i = 0; i < mlength + 1; i++) {
newM = newMatrix(matrix, i);
determinant = determinant + (Math.pow(-1, i) * matrix[0][i]) * det(newM);
}
return determinant;
}
//Format smaller matrix to use in further iteration of above det(int[][]) function
public static int[][] newMatrix(int[][] m, int column) {
int length = m.length - 1;
int[][] newMat = new int[length][length];
for(int i = 1; i < m.length; i++) {
for(int j = 0; j < column; j++)
newMat[i - 1][j] = m[i][j];
for(int k = column + 1; k < m.length; k++)
newMat[i - 1][k - 1] = m[i][k];
}
return newMat;
}
You can adapt to however your Matrix class works.
subMatrix is not really excluding the given row and column - it is just making them zero (not copying) and removing the last row and column...
Printing the matrix will help debug that.
one way: use additional indices for the destination matrix (the sub matrix). Only increment this if a value is really copied. Example: sub.array[k++][l++] = a.array[i][j] inside the if
loop over original matrix
Alternative: if one index is greater than or equal to the index that must be skipped, add 1 to the reading index:
var k = (i>=exclRow) ? i+1 : i;
var l = (j>=exclCol) ? j+1 : j;
sub.array[i][j = a.array[k][l];
code not intended to be complete, just ideas how to solve the problem
When I call the printBoard method it doesn't print anything. Could't find out what I wrote wrong
How could I fix that if the error is nowhere else.
public class Board {
private int rows;
private int cols;
private char[][] Board = new char[rows][cols];
public Board(int row, int col) {
rows = row;
cols = col;
for (int i = 0; i < Board.length; i++) {
for (int j = 0; j < Board[i].length; j++) {
Board[i][j] = '-';
}
}
}
public void printBoard() {
for (int i = 0; i < Board.length; i++) {
for (int j = 0; j < Board[i].length; j++) {
System.out.print(Board[i][j]);
System.out.print("|");
}
System.out.println(" ");
}
}
}
You do not recreate Board in the constructor when you set rows and cols, the array is initialized with default 0 values.
It should be:
public Board(int row, int col) {
rows = row;
cols = col;
Board = new char[rows][cols]; // <-- reset array
for (int i=0; i<Board.length ; i++) {
for (int j=0; j<Board[i].length; j++) {
Board[i][j]='-';
}
}
}
You might have assumed that Board array would be initialized with the values set in the constructor, but in fact the constructor is invoked after initializing the instance variables in the order of their appearance in the class definition.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
The code below will print two square matrices and I need them to perform multiplication between the two matrices but i cant seem to get that part working. I put a comment right before that block of code where the problem is. But for now all it prints is zeros. Iv been looking online at a lot of sites but cant seem to get mine to work.
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
//create the grid
final int rowWidth = 9;
final int colHeight = 9;
Random rand = new Random();
int [][] board = new int [rowWidth][colHeight];
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextInt(10);
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
System.out.println();
int [][] board2 = new int [rowWidth][colHeight];
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
//display output
for(int m = 0; m < board2.length; m++) {
for(int n = 0; n < board[m].length; n++) {
System.out.print(board[m][n] + " ");
}
System.out.println();
}
//error is somewhere here
int[][] calculationMultiplication = new int[rowWidth][colHeight];
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] = calculationMultiplication[l][t] + board[l][z] * board2[z][t];
}
}
}
//display output
System.out.println("\nProduct of the 2 matrices is ");
for (int i = 0; i < calculationMultiplication.length; i++) {
for (int j = 0; j < calculationMultiplication[0].length; j++) {
System.out.print(calculationMultiplication[i][j] + " ");
}
System.out.println();
}
} //end of main
} //end of class Main
The problem is that you've not filled the board2 array, so all its elements will be 0. In the for loop, you should also assign random values to board2. You are doing it twice for the board array.
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board2[row2].length; col2++) { // notice 'board2[row].length'
board2[row2][col2] = rand.nextInt(10);
}
}
You should do something similar in the for loops where you display the array:
//display output
for (int m = 0; m < board2.length; m++) {
for (int n = 0; n < board2[m].length; n++) { // notice 'board2[row].length'
System.out.print(board2[m][n] + " ");
}
System.out.println();
}
board2 is always zero.
You fill the wrong array here:
//fill the grid
for (int row2 = 0; row2 < board2.length; row2++) {
for (int col2 = 0; col2 < board[row2].length; col2++) {
board[row2][col2] = rand.nextInt(10);
}
}
Basically you just did simple copy paste mistakes that can be avoidable if you used methods. I'll tell you how but first here's how you can discover your mistake:
System.out.println(String.format("%d * %d = %d",board[l][z], board2[z][t], board[l][z] * board2[z][t]));
Add this just before doing the calculation for calculationMultiplication[l][t]. Try if you want...
Anyway getting back to your mistakes, you have populated your first matrix only, the second one contain zeros (verify your code in the for loop for inserting random numbers into the second matrix), therefore any number multiplied by zero is equal to zero.
I haven't looked at all your code, because it contain a lot of copy paste which confused you and could confuse any one as well, so here's a better way to avoid mistakes in printing the matrix and inserting random numbers:
Printing:
void printMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
System.out.print(matrix[row][col]+" ");
}
System.out.println(); // new line
}
}
Inserting:
void insertMatrix(int[][] matrix){
for(int row =0; row < numOfRows; row++){
for(int col =0; col < numOfCols; col++){
matrix[row][col] = rand.nextInt(10); // rand must be declared outside any method
}
}
}
Putting all together:
import java.util.*;
public class Main {
// create the grid
final static int rowWidth = 9;
final static int colHeight = 9;
static Random rand;
public static void main(String[] args) {
rand = new Random();
int[][] board = new int[rowWidth][colHeight];
int[][] board2 = new int[rowWidth][colHeight];
int[][] calculationMultiplication = new int[rowWidth][colHeight];
// fill
insertMatrxi(board);
// display output
printMatrix(board);
System.out.println();
// fill
insertMatrxi(board2);
// display output
printMatrix(board2);
for (int l = 0; l < rowWidth; l++) {
for (int t = 0; t < colHeight; t++) {
for (int z = 0; z < rowWidth; z++) {
calculationMultiplication[l][t] += board[l][z] * board2[z][t];
}
}
}
// display output
System.out.println("\nProduct of the 2 matrices is ");
printMatrix(calculationMultiplication);
} // end of main
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println(); // new line
}
}
public static void insertMatrxi(int[][] matrix) {
for (int row = 0; row < rowWidth; row++) {
for (int col = 0; col < colHeight; col++) {
matrix[row][col] = rand.nextInt(10);
}
}
}
} // end of class Main
I'm writing a program that reads a file and sees if the information make up a magic square, but I am getting this error: "java.lang.ArrayIndexOutOfBoundsException: 3" in my sumCol method. Specifically the line below: for (int row = 0; row < square[row].length; row++) {
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square[row].length; row++) {
sum += square[row][col];
}
return sum;
}
I'm not sure if it is necessary, but here is the rest of my class as well:
// ****************************************************************
// Square.java
//
// Define a Square class with methods to create and read in
// info for a square matrix and to compute the sum of a row,
// a col, either diagonal, and whether it is magic.
//
// ****************************************************************
import java.util.Scanner;
public class Square {
int[][] square;
//--------------------------------------
//create new square of given size
//--------------------------------------
public Square(int size) {
square = new int[size][size];
for (int row = 0; row < square.length; row++) {
for (int col = 0; col < square.length; col++) {
square[row][col] = row * 10 + col;
}
}
}
//--------------------------------------
//return the sum of the values in the given row
//--------------------------------------
public int sumRow(int row) {
int sum = 0;
for (int col = 0; col < square.length; col++) {
sum += square[row][col];
}
return sum;
}
//--------------------------------------
//return the sum of the values in the given column
//--------------------------------------
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square[row].length; row++) {
sum += square[row][col];
}
return sum;
}
//--------------------------------------
//return the sum of the values in the main diagonal
//--------------------------------------
public int sumMainDiag() {
int sum = 0;
for (int j = 0; j < square.length; j++) {
sum += square[j][j]; //you can do this because a square's diagonals have the same coordinate points
}
return sum;
}
//--------------------------------------
//return the sum of the values in the other ("reverse") diagonal
//--------------------------------------
public int sumOtherDiag() {
int sum = 0;
for (int j = 0; j < square.length; j++) {
sum += square[j][square.length - 1 - j];
}
return sum;
}
//--------------------------------------
//return true if the square is magic (all rows, cols, and diags have
//same sum), false otherwise
//--------------------------------------
public boolean magic() {
boolean answer = true;
int sum = sumMainDiag();
if (sumOtherDiag() != sum) {
answer = false;
} else {
for (int col = 0; col < square.length; col++) {
if (sum != sumCol(col)) {
answer = false;
}
}
for (int row = 0; row < square.length; row++) {
if (sum != sumRow(row)) {
answer = false;
}
}
}
return answer;
}
//--------------------------------------
//read info into the square from the input stream associated with the
//Scanner parameter
//--------------------------------------
public void readSquare(Scanner scan) {
for (int[] square1 : square) {
for (int col = 0; col < square.length; col++) {
square1[col] = scan.nextInt();
}
}
}
//--------------------------------------
//print the contents of the square, neatly formatted
//--------------------------------------
public void printSquare() {
for (int[] square1 : square) {
for (int col = 0; col < square1.length; col++) {
System.out.print(square1[col] + "\t");
}
System.out.println();
}
}
}
change
row < square[row].length
to:
row < square.length
Perhaps you meant this?
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square.length; row++) {
sum += square[row][col];
}
return sum;
}
Notice that the number of rows is given by square.length, whereas the number of columns in a given row is given by square[row].length.
You're doing the check wrong. Use:
public int sumCol(int col) {
int sum = 0;
for (int row = 0; row < square.length; row++) {
sum += square[row][col];
}
return sum;
}
You're checking the length of the row, not of the overall array.
I think you want
// square.length not square[row].length
for (int row = 0; row < square.length; row++) {
// Here's where we might check square[row].length to be safe.
if (col < square[row].length) {
sum += square[row][col];
}
}
I want to draw a line in java. I will use these draws with making Triangles. I can do this :
1***
11**
111*
1111
and i need to do this:
1***
*1**
**1*
***1
Ive done a lot of work today and my mind got really confused.
Can you help me ? Thanks A lot.
EDIT: also my perfect answer should be Implement Bresenham’s line drawing algorithm but i dont understand in wikipedia.
EDIT 2: my grid code :
String [][] matrix = new String [50][50];
for (int row = 0; row < 50; row++){
for (int column = 0; column < 50; column++){
matrix [row][column] = "*";
}
}
public class Test
{
public static void main(String [] args)
{
int size=50;
String[][] matrix= new String [size][size];
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
if (i != j)
matrix[i][j]="*";
else
matrix[i][j]="1";
}
}
for (int i=0; i < size; i++)
{
for (int j=0; j < size; j++)
{
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
}
Edit: if it's already filled with * simply make matrix[i][j]="1"; when i equals j, ie if (i==j).
public class MulArray {
public static void main(String[] args) {
/*
* 1*** 1** 1* 1
*/
String[][] grid = new String[5][5];
for (int row = 0; row < grid.length-1; row++) {
for (int column = 0; column < grid[row].length; column++) {
if (row == column) {
grid[row][column] = "1";
} else {
grid[row][column] = "*";
}
}
}
for (int row = 0; row < grid.length-1; row++)
for (int column = 0; column < grid[row].length; column++) {
if (column != 4) {
System.out.print(grid[row][column]);
}
else{
System.out.print("\n");
}
}
}
}