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
Related
I'm trying to create a 2D int array of numbers that are the product of 2 via user input defining the length of the rows and columns, as the one below:
1 2 4 8
2 4 8 16
4 8 16 32
8 16 32 64
I've only got up to here, and cannot figure out how to make the matrix to start from 1 and to look like the one above. I'd appreciate your help on this one!
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = temp * 2;
temp *= 2;
}
}
System.out.println(Arrays.deepToString(matrix));
I'd say that each element of the matrix would be:
matrix[i][j] = (int) Math.pow(2, i+j) ;
So, your loop would look like this:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = (int) Math.pow(2, i+j);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
temp = (int)Math.pow(2, i);
for (int j = 0; j < n; j++) {
matrix[i][j] = temp;
temp *= 2;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
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]);
}
}
}
I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
I try to convert 1D to 2D array, but I keep getting java.lang.ArrayIndexOutOfBoundsException, and I have tried whatever I could find on the stackoverflow or internet, but I do not understand why I have this issue?
public class Arrayto2DArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j]);
}
System.out.println();
}
}
}
I kind of know why I get this error and it because of this line
b[i][j] = a[i+j*4];
but I cannot come up any formula better than this.
Consider the second for-loop
Lets say when i = 3 and j= 3
a[i+j*4] evaluates to a[15] which is out of the array
When you declare you 2-d array, you specified int[][] b = new int[4][];, meaning that the first inner for loop for (int j = 0; j < b[i].length; j++) should result in a NullPointerException since b[i].length has no predefined length. Before intering the inner for loop, you should define the size of each b[i] like b[i] = new int[somenumber]
In regards to convert the 1d loop to a 2d, you need to define the rule around spliting it into the 2-d array. Then accordingly the second for loop need modification
EDIT:You modified your code to have an int[4][4] array, which means you have 16 placeholders. Your 1-d array contain only 8 placeholders. It depends on how you want to sort the array, like it can be
b 0 1 2 3
0 0 1 6 83
1 4 5 12 7
2 0 0 0 0
3 0 0 0 0
or any other pattern
Assuming the length of 1-d array is 8 and the total index of 2-d array is 16, the following is more of a general solution:
public static void main(String[] args) {
// TODO code application logic here
int[] a = { 0, 1, 6, 83, 4, 5, 12, 7 };
int[][] b = new int[4][4];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j] = 0;
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try {
if ((j + i * 4) < a.length)
b[i][j] = a[j + i * 4];
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(b[i][j] + "\t");
}
System.out.println();
}
}
What is wrong is your 2D array is a 4*4, so that means for each index, there will be 4 elements i.e. say values. So there would be a total of 16 values, so you would need a 1D array with 16 elements for the above code to work. Right now you have only 8 values in your 1D array.
I think your code should change like this
public class Arrayto2DArray {
public static void main(String[] args) {
// TODO code application logic here
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
b[i][j]=0;
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < b[i].length; j++) {
try{
b[i][j] = a[i+j*4];
}catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}
Your correct formula should be like.
int[] a = {0,1, 6, 83, 4, 5, 12, 7};
int[][] b = new int[4][2];
int k=0;
for (int i = 0; i < b.length; i++) { // Column of 2D array
for (int j = 0; j < b[0].length; j++) { // Row of 2D array
b[i][j]= a[k++];
System.out.println(b[i][j]);
}
}
Edit:
For general case, If your row is fixed at 4 but column is not fixed than your 2D conversion formula should be like below.
int col = a.length / 4;
int remainder = a.length % 4;
if (remainder > 0) {
col = col + 1; // Get the correct column size.
}
int[][] b = new int[4][col];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < col; j++) {
if (k < a.length) {
b[i][j] = a[k];
System.out.println(b[i][j]);
}
k++;
}
}
I have to sort elements in each row and then display the array.
For example, if the input array is:
5 1 3 1 3 5
INPUT: 7 6 4 OUTPUT: 4 6 7
9 8 2 2 8 9
My code for that was:
for (int i = 0; i < size; i++) { //"size" is the size of the square matrix
for (int j = 0; j < size; j++) {
for (int k = 0; k < size - 1; k++) {
for (int l = 0; l < size - k - 1; l++) {
if (arr[i][j] > arr[i][j+1]) { //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][j+1];
arr[i][j+1] = temp;
}
}
}
}
}
Any suggestions?
for (int i = 0; i < size; i++){ //"size" is the size of the square matrix
for (int j = 0; j < size; j++){
for (int k = j+1; k < size; k++){
if (arr[i][j] > arr[i][k]){ //arr[][] is of datatype int
int temp = arr[i][j];
arr[i][j] = arr[i][k];
arr[i][k] = temp;
}
}
}
}
I don't think you need 4th loop
I would do it simpler
for(int[] r : arr){
Arrays.sort(r);
}
I would create a method to sort rows, and then just iterate through the rows in the matrix and sort them one at a time. For example:
public static int[] sortRow(int[] row) // selection sort
{
for (int i = 0; i < row.length - 1; i++) {
for (int j = i + 1; j < row.length; j++) {
if (row[i] > row[j]) {
int temp = row[i];
row[i] = row[j];
row[j] = temp;
}
}
}
return row;
}
public static void main(String args[])
{
int[][] arr = {{5, 1, 3}, {7,6,4}, {9,8,2}};
for (int r = 0; r < arr.length; r++) { // for every row in the matrix
arr[r] = sortRow(arr[r]); // set the row to be the sorted row
}
// print out the array to the console
for (int r[] : arr) {
for (int c : r)
System.out.print(c + " ");
System.out.println();
}
}
Output:
1 3 5
4 6 7
2 8 9