Änderungen Matrix

This commit is contained in:
Sebastian Brosch 2024-01-30 17:09:21 +01:00
parent f30fe63db7
commit 4019f76373
2 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,35 @@
class Aufgabe {
public static void main(String[] args) {
Matrix matrix1 = new Matrix(3,1);
matrix1.setValue(1,1,5);
matrix1.setValue(2,1,4);
matrix1.setValue(3,1,8);
Matrix matrix2 = new Matrix(3,1);
matrix2.setValue(1,1,9);
matrix2.setValue(2,1,3);
matrix2.setValue(3,1,4);
System.out.println("Matrix 1:");
matrix1.print();
System.out.println("Matrix 2:");
matrix2.print();
System.out.println("Matrix 1 nach Multiplikation mit 5:");
matrix1.multiply(5);
matrix1.print();
System.out.println("Matrix 1 nach Addition mit Matrix 2:");
matrix1.add(matrix2);
matrix1.print();
System.out.println("Matrix 2 nach Multiplikation mit Matrix 1:");
try {
matrix2.multiply(matrix2);
matrix2.print();
} catch(MatrixException e) {
System.out.println("Fehler beim Multiplizieren zweier Matrizen: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,84 @@
public class Matrix {
private int rows = 0;
private int columns = 0;
private int[][] matrix;
Matrix(int rows, int columns) {
this.rows = rows;
this.columns = columns;
this.init();
}
private void init() {
this.matrix = new int[this.rows][this.columns];
for(int r = 0; r < this.rows; r++) {
for(int c = 0; c < this.columns; c++) {
this.setValue(r+1, c+1, 0);
}
}
}
int getValue(int row, int column) {
return this.matrix[row-1][column-1];
}
int getNumberOfColumns() {
return this.columns;
}
int getNumberOfRows() {
return this.rows;
}
void setValue(int row, int column, int value) {
this.matrix[row-1][column-1] = value;
}
void multiply(int scalar) {
for(int r = 0; r < this.rows; r++) {
for(int c = 0; c < this.columns; c++) {
this.matrix[r][c] *= scalar;
}
}
}
void multiply(Matrix matrix) {
if(isSameSize(matrix)) {
for(int r = 0; r < this.rows; r++) {
for(int c = 0; c < this.columns; c++) {
this.matrix[r][c] *= matrix.getValue(r+1, c+1);
}
}
} else {
throw new MatrixException();
}
}
boolean isSameSize(Matrix matrix) {
return this.getNumberOfColumns() == matrix.getNumberOfColumns() && this.getNumberOfRows() == matrix.getNumberOfRows();
}
void add(Matrix matrix) {
if(this.getNumberOfColumns() == matrix.getNumberOfColumns() && this.getNumberOfRows() == matrix.getNumberOfRows()) {
for(int r = 0; r < this.rows; r++) {
for(int c = 0; c < this.columns; c++) {
this.matrix[r][c] += matrix.getValue(r+1, c+1);
}
}
}
}
void print() {
for(int r = 0; r < this.rows; r++) {
for(int c = 0; c < this.columns; c++) {
System.out.printf("%5d", this.getValue(r+1, c+1));
}
System.out.print("\n");
}
}
}
class MatrixException extends RuntimeException {
}