How to write a method for a transposed matrix? - java

I am trying to create an application class MatrixApplication, in which the user first enters the number of rows and columns of the matrix.
This will be used to create an array object.
Then the elements of the Matrix are called up row by row and column by column. When all elements have been read in, they are assigned to the matrix object.
Next, the array is transposed and finally the transposed array is displayed.
How do I assign the elements to the Matrix object?
How do I display a transposed array?
package domain;
public class Matrix {
private int[][] numbers;
public Matrix(int rows, int columns) {
setNumbers(numbers);
if (rows < 1)
rows = 1;
else
rows = rows;
if (columns < 1)
columns = 1;
else
columns = columns;
numbers = new int[rows][columns];
}
public final void setNumbers(int[][] numbers) {
this.numbers = numbers;
}
public int[][] getNumbers() {
return numbers;
}
public int[][] transpose() {
int[][] transpose = new int[numbers[0].length][numbers.length];
for (int i = 0; i < numbers.length; ++i) {
for (int j = 0; j < numbers[0].length; ++j) {
transpose[j][i] = numbers[i][j];
}
}
return transpose;
}
}
package ui;
import java.util.Scanner;
import domain.Matrix;
public class MatrixApplication {
public static void main (String[]args)
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of rows of the matrix:");
int rows = input.nextInt();
System.out.print("nter the number of columns of the matrix:");
int colums = input.nextInt();
Matrix matrix = new Matrix(rows, colums);
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
}
System.out.printf("The transposed matrix: %d",matrix.transpose());
}
}
And if I want this form of transposed matrix:
example of a 4x2 array to a 2x4 array

Simply read the numbers into a two-dimensional array and call matrix.setNumbers.
final int[][] numbers = new int[rows][colums];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < colums; ++j) {
System.out.printf("Enter the element of row %d and column %d: ", i + 1, j + 1);
numbers[i][j] = input.nextInt();
}
}
matrix.setNumbers(numbers);
System.out.printf("The transposed matrix: %s", Arrays.deepToString(matrix.transpose()));

Related

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

How to Create Method for Finding Largest Element in Array

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int numberOfRows, numberOfColumns;
double arrayElements[][] = null;
int index[] = null;
System.out.print("Enter number of rows in array: ");
numberOfRows = keyboard.nextInt();
System.out.print("Enter number of columns in array: ");
numberOfColumns = keyboard.nextInt();
arrayElements = new double[numberOfRows][numberOfColumns]; //this command allocates memory for the array arrayElements
for (int row = 0; row < numberOfRows; row++)
{
for (int column = 0; column < numberOfColumns; column++)
{
System.out.print("Enter the Value for Row [" + row + "], Column " + "[" + column + "]: ");
arrayElements[row][column] = keyboard.nextDouble();
}
}
System.out.printf("\n Two-Dimensional Array: %d rows x %d columns\n", numberOfRows, numberOfColumns);
for (int row = 0; row < numberOfRows; row++)
{
System.out.printf("Row %3d:", row);
for (int column = 0; column < numberOfColumns; column++)
{
System.out.printf("%7.1f", arrayElements[row][column] );
}
System.out.println();
index = locateLargest( arrayElements );
}
}
public static int[] locateLargest( double[][] arrayx2 ){
}
Hello all,
I am trying to write a method for finding the largest element in a two-dimensional array, and return the index of the element with the highest value to the single-dimensional array 'index'. I have the signature written, but can anyone please help me figure out how to actually write the method that will search each element of the two-dimensional array and find the index location of the largest number?
Thank you so much!
/*Finds max value in an Array*/
public int maxValue(int array[]){
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return Collections.max(list);
}
For 2 dimensional array use that:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Reference: https://stackoverflow.com/a/5877271/1848929
Firstly, if you want the returned array of your method to contain the largest element as well as the index, the return type should be double[] and not int[] since the type of the elements of the matrix is double. The method bellow will return an array containing three elements. the first element is the row index, the second is the column index, and the third is the element value. if you are going to use the code bellow, make sure to change the return type and also the type of index in your code to double[]. I hope this is helpful.
// first we assume the largest element is the one located at row 0, and
//column 0, then we compare it with the other elements in the matrix
public static double[] locateLargest( double[][] arrayx2 ){
double max = arrayx2[0][0];
int row = 0, col = 0;
double[] indexAndMaxVal = new double[3];
for (int i = 0; i < arrayx2.length; i++) {
for (int j = 0; j < arrayx2[i].length; j++) {
if (arraux2[i][j] > max) {
maxValue = arrayx2[i][j];
row = i;
col = j
}
}
}
indexAndMaxVal[0] = row;
indexAndMaxVal[1] = col;
indexAndMaxVal[2] = max;
return indexAndMaxVal;
}

Adding values on 2d array java

I have created a program that lets the user input the number of rows and columns they want in a 2d array and then it fills the array with all even numbers starting from 0.
I have to add all the numbers in the array to get a total sum and I have no idea how to do that. The rest of my program is complete I'm just having trouble with the sum.
Here is my code:
import java.util.*;
public class ArrayOver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many rows? ");
int x = scan.nextInt();
System.out.println("How many columns? ");
int y = scan.nextInt();
int[][] nums = new int[x][y];
fillArray(nums);
displayArray(nums);
System.out.println();
}
public static void fillArray(int nums[][]) {
int count = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length ; col++) {
nums[row][col] = count;
count++;
count++;
}
}
}
public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {
System.out.println(Arrays.toString(nums[row]));
}
}
}
Try this:
public static void countArray(int[][] nums)
{
int total=0;
for (int row=0;row<nums.length;row++)
for (int col=0;col<nums[0].length;col++)
total += nums[row][col];
System.out.println(total);
}
This should go through all the numbers in the array and add their values to total.
If you want sum all elements of array, just do it:
int sum = 0;
for(int row = 0; row < nums.length ; row++) {
for (int col = 0; col < nums[row].length ; col++) {
sum = sum + nums[row][col];
}
}

Trying to multiply 2d arrays (like in matrix multiplication), but only works for square matrices

I am a complete Java newbie and I was trying to multiply two 2D arrays like you would multiply two matrices. The program below only works for square matrices, but not for others. I cannot seem to figure out where I am going wrong. If someone could help me out, it would be great.
import java.util.Scanner;
public class TwoDMatrix {
public static void main (String [] args){
Scanner scanme = new Scanner(System.in);
//Input dimensions of Matrix A
System.out.println("Enter the dimensions (row x column) of Matrix A");
int rowA = scanme.nextInt();
int columnA = scanme.nextInt();
int [][] matA = new int [rowA][columnA];
//Input dimensions of Matrix B
System.out.println("Enter the dimensions (row x column) of Matrix B");
int rowB = scanme.nextInt();
int columnB = scanme.nextInt();
int [][] matB = new int [rowB][columnB];
// Declaring new variables
int [][] product = new int [columnA][rowB];
int rowCountA, columnCountA, rowCountB, columnCountB;
int rowCountProduct, columnCountProduct;
int sum;
String divider = "---------";
// Input values of Matrix A
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%s%d%s%d%s", "Enter the value at A(", rowCountA, ",", columnCountA, ")");
matA[rowCountA][columnCountA] = scanme.nextInt();
}
}
// Input values of Matrix B
for (rowCountB = 0; rowCountB < rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%s%d%s%d%s", "Enter the value at B(", rowCountB, ",", columnCountB, ")");
matB[rowCountB][columnCountB] = scanme.nextInt();
}
}
//Calculate product of the two matrices
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
sum = 0;
for (columnCountA=0, rowCountB=0; columnCountA<columnA && rowCountB<rowB; columnCountA++, rowCountB++){
sum += (matA[rowCountProduct][columnCountA] * matB[rowCountB][columnCountProduct]);
}
product[rowCountProduct][columnCountProduct] = sum;
}
}
//Prints the input matrix A
System.out.printf("%n%s%n%s%n", "Matrix A:", divider);
for (rowCountA = 0; rowCountA < rowA; rowCountA++){
for (columnCountA = 0; columnCountA < columnA; columnCountA++){
System.out.printf("%5d", matA[rowCountA][columnCountA]);
}
System.out.println();
}
//Prints the input matrix B
System.out.printf("%n%s%n%s%n", "Matrix B:", divider);
for (rowCountB = 0; rowCountB< rowB; rowCountB++){
for (columnCountB = 0; columnCountB < columnB; columnCountB++){
System.out.printf("%5d", matB[rowCountB][columnCountB]);
}
System.out.println();
}
//Prints the product
System.out.printf("%n%s%n%s%n", "Product", divider);
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
System.out.printf("%5d", product[rowCountProduct][columnCountProduct]);
}
System.out.println();
}
}
}
It has been a while since I learned linear algebra, but I think when you multiply a matrix A[n1][m1] by a matrix B[n2][m2], m1 must be equal to n2 and the result should be a matrix C[n1][m2].
Therefore
int [][] product = new int [columnA][rowB];
should be
int [][] product = new int [rowA][columnB];
And you should verify that columnA == rowB before you start the multiplication.
You have quite a complicated condition here :
for (columnCountA=0, rowCountB=0; columnCountA<columnA && rowCountB<rowB; columnCountA++, rowCountB++){
sum += (matA[rowCountProduct][columnCountA] * matB[rowCountB][columnCountProduct]);
}
Remember the mathematic formula :
be A a n x l matrix, B a l x m matrix, then
forall (i,j) in [1,n]x[1,m], (AB)(i,j) = sum_(k in [1,l]) { A(i,k).B(k,j) }
Therefore, a pseudo-code for this is :
for (int i=0 ; i<A.length ; i++) {
for (int j=0 ; j<B[0].length ; j++) {
prod[i][j] = 0;
for (int k=0 ; k<A[0].length ; k++) {
prod[i][j] += A[i][k]*B[k][j];
}
}
}
Basically, you define your product matrix as:
int [][] product = new int [columnA][rowB];
This means it should have as many rows as there are columns in A, and as many columns as there are rows in B.
But then, when you loop to fill it, this is your loop:
for (rowCountProduct = 0; rowCountProduct < rowA; rowCountProduct++){
for (columnCountProduct = 0; columnCountProduct < columnB; columnCountProduct++){
...
}
}
This means that you're trying to fill the rows in the product, which are supposed to be in the range 0 ≤ rowCountProduct < columnA with values in the range 0 ≤ rowCountProduct < rowA. Similarly, you run the columns to the range columnB instead of rowB as you defined it.
So you should either change the definition of your matrix, or change the way you fill your matrix up.

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Categories

Resources