Implementing vector multiplication in java - java

Currently I'm trying to implement a way to be able to use vector- and matrix-multiplication in java, right now I have the code:
package ai2;
public class MyMatrix {
int[][] alpha;
int a;
int b;
int rowsB;
int colsB;
public MyMatrix(int a, int b) {
this.a = a;
this.b = b;
alpha = new int[a][b];
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
alpha[k][l] = 0;
}
}
}
public void insertValue(int o, int q, int z) {
this.alpha[o][q] = z;
}
public void print() {
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
System.out.print(this.alpha[k][l] + " ");
}
System.out.println();
}
}
public void multiplyMatrix(MyMatrix B) {
MyMatrix created = new MyMatrix(this.a, B.b);
for (int m = 0; m < a; m++) {
for (int k = 0; k < b; k++) {
for (int l = 0; k < this.a; l++) {
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
}
}
}
}
public static void main(String[] args) {
MyMatrix a = new MyMatrix(2, 2);
a.insertValue(0, 0, 1);
a.insertValue(1, 1, 1);
a.print();
MyMatrix b = new MyMatrix(2, 2);
b.insertValue(0, 0, 1);
b.insertValue(1, 0, 1);
// System.out.println(a);
}
}
The problem is my multiplyMatrix method, it takes a MyMatrix object but I cant reach the values using for example:
MyMatrixA[k][l]
I need some sort of idea to reach those values or perhaps a smarter implementation, I cannot use packages outside of java, thankful for any help!

Square brackets in Java are only for accessing array elements.
Your syntax there will not compile, and you cannot access your matrix elements that way.
Why don't you just implement a getAlpha getter in your MyMatrix class that returns the value for alpha (or better, a copy thereof, to ensure immutability)?
You could then reference it with theMatrixInstance.getAlpha()[k][l].
You could also simplify a bit and implement a get method taking two indices.
That would allow you to check whether the given indices are within the bounds of your two-dimensional array and throw a custom exception (or return some default value) rather than the ArrayIndexOutOfBoundsException you'd otherwise get.

Replace this line
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
with
created.alpha[i][j] += this.alpha[i][k] * B.alpha[k][j];
Or better yet, replace
MyMatrix created = new MyMatrix(this.a, B.b);
with
MyMatrix A = this;
MyMatrix C = new MyMatrix(this.a, B.b);
then you can do
C.alpha[i][j] += A.alpha[i][k] * B.alpha[k][j];
Which reads a little more clearly.
Finally, no need to initialize alpha with 0's in your constructor, this happens automatically.

Related

how to add two arrays together using a method

I am trying to add to lists together. ( I know my class name is not right for it, but whatever)
The problem I am facing is where i have the code:
C[i] = v[i] + x[i];
it says the type of expression must be an array but resolved into a variable.....any suggestions how to get around with it and be able to add two arrays together using a method??
import java.util.Arrays;
public class reverse {
int n;
double [] arr;
public reverse( int input){
n =input;
arr = new double[n];
}
public double[] get_array(){
for (int i = 0; i < n; i ++)
{
arr[i] = i + 1;
}
return arr;
}
public reverse add(reverse v, reverse x){
reverse C = new reverse(3);
for( int i = 0; i < n; i++){
C[i] = v[i] + x[i];
System.out.println(C[i]);
}
return C;
}
public static void main(String[] args){
reverse A = new reverse(5);
reverse B = new reverse(5);
System.out.println( Arrays.toString(A.get_array()));
System.out.println( Arrays.toString(B.get_array()));
}
}
To get the individual arrays from v and x call get_array(). Also, by convention the method get_array() should be getArray() and the class reverse should be Reverse. To correctly size C, get the lengths of v and x and take the max (or the min if you only want elements that appear on both sides). Iterate and add the values, storing the result in C's array. Something like,
public reverse add(reverse v, reverse x) {
reverse C = new reverse(Math.max(v.n, x.n));
double[] vals = C.get_array(), left = v.get_array(), right = x.get_array();
for (int i = 0; i < C.n; i++) {
if (i < left.length && i < right.length) {
vals[i] = left[i] + right[i];
} else if (i < left.length) {
vals[i] = left[i];
} else {
vals[i] = right[i];
}
}
return C;
}
As mentioned, if you only want to add elements present on both sides, then the code can be simplified. Use Math.min to get the correct length and you can eliminate the array length checks. Like,
public reverse add(reverse v, reverse x) {
reverse C = new reverse(Math.min(v.n, x.n));
double[] vals = C.get_array(), left = v.get_array(), right = x.get_array();
for (int i = 0; i < C.n; i++) {
vals[i] = left[i] + right[i];
}
return C;
}
The problem is that by saying reverse C;, you are not creating an array, therefore you cannot use C[i].
public reverse add(reverse v, reverse x){
reverse C = new reverse(3);
for( int i = 0; i < n; i++){
//Replace C with C.arr
C.arr[i] = v[i] + x[i];
System.out.println(C.arr[i]);
}
return C;
}
Here C.arr refers to arr field in C
Also by convention type name should start with a capitalized letter
C,v, and x are Objects of type Reverse, not arrays. You need to access the arrays within the objects.
C.arr[i] = v.arr[i] + x.arr[i];
System.out.println(C.arr[i]);
Also, you don't allow for the fact that they might not be the same size arrays. You might need to allow for that.

2D array - specify amount to new 2d array

I have a 2-d array of double numbers it's 48 by 48, I am trying to make a method that will allow the user to select a specific amount e.g. = 7 by 7 and then put that into a new 2d array.
public static double[][] amountOTP(double [][] a, int x){
a = new double[x][x];
return a;
}
thats all i have right now, this takes an 2d array as input however even though i specified x it doesn't work.
When you want to cut it ro a smaller size and copy the part of the original array, this should work:
public static double [][] cutArray (double [][] a, int newSize){
if (x > a.length)
throw new IllegalArgumentException ("Can only make array smaller");
double [][] b = new double [newSize][newSize];
for (int i = 0; i < newSize; i++){
for (int j = 0; j < newSize; j++){
b [i][j] = a [i][j];
}
}
return b;
}
The solution below considers situations in which the requested new two-dimensional array length is greater than the original in which case we simply return the original.
Example:
public static double[][] amountOTP(double [][] a, int x){
if(x > a.length) return a;
for (double[] arr : a)
if(arr.length < x)
return a;
double[][] newArray = new double[x][x];
for (int i = 0; i < x; i++)
for (int j = 0; j < x; j++)
newArray[i][j] = a[i][j];
return newArray;
}
Sorry if I'm wrong, but I'm assuming for now that you want your method to return a smaller 2d array which contains some of the values of the given array, in which case you would need to change your method to this:
public static double[][] amountOTP(double [][] a, int x) {
double[][] b = new double[x][x];
x = Math.min(x, a.length);
for(int i = 0;i < x; i++)
for(int j = 0;j < x; j++)
b[i][j] = a[i][j];
return b;
}
This should work fine but feel free to comment and inform me if I left anything out or it doesn't work; I'm here to help. Anyways, I hope this works for you. (Also, if this isn't the answer you were looking for, feel free to tell me.)
Note: This should avoid IndexOutOfBounds exceptions, so it will still work correctly if the user gives an x value bigger than the size of a. The 2d array that this method returns will just have some values of zero where it couldn't find any numbers.
I think it's something like that you're looking for :
public static double[][] amountOTP(double [][] a, int x){
double [][] ret = new double[x][x];
for(int i = 0; i < x; i++)
for(int j = 0; j < x; j++)
ret[i][j] = a[i][j];
return ret;
}
But you have to be careful with the parameters because it can cause an IndexOutOfBounds exception
I see you already have a lot of answers, but nobody was making use of the excellent Arrays.copyOf Java API method:
public static double[][] amountOTP(double [][] a, int x){
a = Arrays.copyOf(a, x);
for(int i=0; i<a.length; i++) {
if(a[i] != null) {
a[i] = Arrays.copyOf(a[i], x);
} else {
a[i] = new double[x]; // allows growth
}
}
return a;
}
you are actually not yet initializing the array so the method should be like this
public static void main(String[] args)
{
double[][] a=amountOTP(3);
for(int j=0;j<a.length;++j)
{
for(int i=0;i<a[j].length;++i)
{
a[j][i]=2;
}
}
for(int j=0;j<a.length;++j)
{
for(int i=0;i<a[j].length;++i)
{
System.out.println(a[j][i]);
}
}
}
public static double[][] amountOTP(int x)
{
return new double[x][x];
}

Why does this code in java print a reference instead the result of invoking the method?

I am supposed to write a method that accepts 3 2-D arrays of This method should determine whether one of the matrices is the result of matrix addition of the other two.
public class Matrix {
public static void main(String[]args){
int [][] a = {{5,2,3},{4,1,6},{0,7,2}};
int [][] b = {{1,2,3},{4,5,6},{0,1,2}};
int [][] t = {{6,4,6},{8,6,12},{0,8,4}};
System.out.println(add(a,b));
System.out.println(check(a,b,t));
}
public static int [][] add(int[][]a,int[][]b){
int i=0;
int j=0;
int[][] r = new int [3][3];
while (i<a.length){
r[i][j] = a[i][j] + b[i][j];
i++;
j++;
}
return r;
}
public static boolean check(int[][]a,int[][]b,int[][]t){
int i = 0;
int j = 0;
while(i<t.length){
if(t==add(a,b))
return true;
}
return false;
}
}
add returns an array. Arrays in Java are objects, but they do not override the toString() method. When printing, you'd print their default toString() call, which is implemented by Object as return getClass().getName() + "#" + Integer.toHexString(hashCode());.
Luckily, Java provides a utility in the form of java.util.Arrays.deepToString(Ojbect[]) to generate a more readable string output:
System.out.println(Arrays.deepToString(add(a,b)));
EDIT:
Your add method is also wrong. Your code iterates i and j together, so it only sums the elements along the matrix's diagonal instead of adding all of them. You should use a nested loop instead:
public static int [][] add(int[][]a, int[][]b) {
int[][] r = new int [3][3];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
r[i][j] = a[i][j] + b[i][j];
}
}
return r;
}
Your check method, by the way, is also wrong - it attempts to compare the array itself instead of is elements:
public static boolean check(int[][]a, int[][]b, int[][]t) {
int[][] r = add(a, b);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (r[i][j] != t[i][j]) {
return false;
}
}
}
return true;
}

Finding intersection of two sorted arrays in Java

public class intersect {
public static void find(int[] a, int[] b, int[] acc)
{
int position = 0;
for (int j = 0; j < a.length; j++) {
for (int k = 0; k<b.length; k++) {
if (a[j] == b[k]) {
acc[position] = b[k];
position++;
}
}
}
System.out.println(java.util.Arrays.toString(acc));
}
public static void main (String[] s)
{
int[] acc = new int[2];
int[] a = {1,2,3};
int[] b = {2,3,4};
find(a, b, acc);
}
}
I have written the above code to solve the problem.
But if you see, the function is very limited because I have to change the length of the acc every time. That means I have to know how many elements are intersecting. In this case, the array {1,2,3} and {2,3,4} have {2,3} in common, so the length of the acc would be 2.
I am sure there are millions of ways of tackling this problem, but I cannot seem to think of a way of fixing this.
Please help!
If your professor wants you to use arrays, you can use the following method:
public static int[] resize(int[] arr)
{
int len = arr.length;
int[] copy = new int[len+1];
for (int i = 0; i < len; i++)
{
copy[i] = arr[i];
}
return copy;
}
This will increase the size of the array by 1. You can use that instead. By the way, you're not using the fact that they're sorted in your find() method. What you should do is this:
public static void find(int[] a, int[] b, int[] acc)
{
int a_index = 0, b_index = 0, acc_index = -1;
int a_element, b_element;
while (a_index < a.length && b_index < b.length)
{
a_element = a[a_index]; b_element = b[b_index];
if (a_element == b_element)
{
acc = resize(acc);
acc[++acc_index] = a_element;
a_index++; b_index++;
} else if (b_element < a_element) {
b_index++;
} else {
a_index++;
}
}
System.out.println(java.util.Arrays.toString(acc));
}
This method is more efficient now. Working example.
To find intersection of 2 sorted arrays, follow the below approach :
1) Use two index variables i and j, initial values with 0
2) If array1 is smaller than array2 then increment i.
3) If array1 is greater than array2 then increment j.
4) If both are same then print any of them and increment both i and j.
check this link for more information
https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/
public class FindIntersection {
static void findInterSection(int array1[], int array2[], int array1NoOfElements, int
array2NoOfElements) {
int i = 0, j = 0;
while (i < array1NoOfElements && j < array2NoOfElements) {
if (array1[i] < array2[j]) {
i++;
} else if (array2[j] < array1[i]) {
j++;
}
// if both array elements are same
else {
System.out.println(array2[j++] + " ");
i++;
}
}
}
public static void main(String[] args)
{
int myFirstArray[] = { 1, 2, 4, 5, 5 };
int mySecondArray[] = { 2, 3, 5, 7 };
int m = myFirstArray.length;
int n = mySecondArray.length;
findInterSection(myFirstArray, mySecondArray, m, n);
}
}
Make your intersection array's size the size of the smaller of your original arrays. That way, you won't ever have to increase it's capacity.
Then you can use Arrays.copy to transfer your results into an appropriately sized array.
Not sure if this is the best solution, but you don't need to hard-code the size of the intersection ahead of time (which is one thing you were concerned about).
As you iterate through both arrays, you can add elements found in both sets to a StringBuilder (along with some delimiter, I used a comma in the example below). Once you're finished, you can call toString() & then split() using the delimiter afterwards to get a String[]. At that point, you can put convert those String objects to int primitives & return an int[].
public class Scratch {
public static void main(String[] s) {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
int[] intersection = findIntersection(a, b);
System.out.println(Arrays.toString(intersection));
}
public static int[] findIntersection(int[] a, int[] b) {
StringBuilder intersectionStringBuilder = new StringBuilder();
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < b.length; k++) {
if (a[j] == b[k])
intersectionStringBuilder.append(a[j] + ",");
}
}
String[] intersectionStringArray = intersectionStringBuilder.toString().split(",");
int[] intersection = new int[intersectionStringArray.length];
for (int current = 0; current < intersectionStringArray.length; current++) {
intersection[current] = Integer.parseInt(intersectionStringArray[current]);
}
return intersection;
}
}
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j] && !index.contains(j)){
list.add(arr1[i]);
index.add(j);
break;
}
}
}
int result[]=new int[list.size()];
int k=0;
for(int i:list){
result[k]=i;
k++;
}
for(int i=0;i<result.length;i++){
System.out.println(result[i]);
}
return result;
}

How to acces Matrix as an object

I have an object calld Matice. Matice is a matrix nxn filled with random numbers in a set range. I want to perform some operations on my objects like adding, multiplying, inversion, etc. How can i do that? If i try something like m1[i][j] * m2[j][i].
but i get error message.
public class Main {
public static void main(String[] args) {
Matice m1 = new Matice(3);
m1.matrixFill(0, 5);
m1.matrixPrint();
//m1.matrixAdd(m2);
}
}
public class Matice {
int[][] matice;
private int n;
public Matice(int n) {
this.n = n;
if(n > 0) {
matice = new int[n][n];
}
}
public void matrixPrint(){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.format("%5d", matice[i][j]);
}
System.out.println("");
}
System.out.println("");
}
public void matrixFill(int a, int b){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matice[i][j] = (int) (Math.random() * (a + b + 1) - a);
}
}
}
public void matrixAdd(Matice m1, Matice m2){
int[][] resultMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
resultMatrix[i][j] = m1[i][j] + m2[i][j];
}
}
}
}
You are referring to the object itself not the array that is the field of object.
Try this:
resultMatrix[i][j] = m1.matice[i][j] + m2.matice[i][j];
instead of
resultMatrix[i][j] = m1[i][j] + m2[i][j];
btw. I recommend to mark matrixAdd to static because it is a stateless, helper method or extract into a different class.
You already started the right way: by adding the operations as methods to your Matice class. Unlike C++, you can not define operators for your class. You'll have to stick with ordinary methods.
Your methods should use the Matice they are called on as one argument. Thus use something like add(Matice other) Next you'll have to decide if you methods modify the Matice they are called on, or if they return a copy of the data.
Last but not least, if this isn't a toy/exercise project, I'd check out existing libraries: Java matrix libraries

Categories