Having trouble multiplying two matrices - java

Sorry,this is a homework problem. I am not good with maths, so I checked out some videos to understand how two matrices are multiplied. I came up with a formula, but I do not know what I am doing wrong? This question has been answered before, but I did not understand. Thank you.
case 3:
System.out.println("THE PRODUCT OF TWO MATRICES ARE: ");
for(i =0; i< arrayList.length; i++){
for(j =0; j< arrayList1.length; j++){
for(k =0; k < arrayList1.length;k++){
multiplication = arrayList[i][k] * arrayList1[k][j] + multiplication;
}
System.out.print(arrayList[i][j]+" ");
}
System.out.println();
}
break;

First of all you should understand that the multiplication of two matrices should result in a matrice (which not appear to be the case with your multiplication variable).
I suppose you have to program the basic implementation. Let's take a look at the following matrices.
A has n rows, and m columns; said to be a matrice n x m.
Similary, B has m rows and p columns (m x p matrice). The multiplication of A x B will give you a matrice n x p.
Note that if you want to do the multiplication A x B, the matrice A must have the same number of columns that the number of rows of the matrice B.
Now each value in the matrice AB (ith row and jth column) is computed as follow:
That said, let's take a look at the Java implementation (which is a pure translation of the mathematical formula).
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int[][] result = new int[matrixA.length][matrixB[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
for (int k = 0; k < matrixB.length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
The result matrice is initialized at the right dimensions. Then the first two nested loop (with indices i and j) will loop through all the elements of elements of the resulting matrice. Then you just need the third loop to compute the sum.
You'd still need to check that the matrices you give as parameters have the correct length.
The algorithm used is pretty naive (O(n3) complexity). If you don't understand it, there's a lot of resources in the web that explains how it works; but that would more a mathematical question than a programming one.
Hope it helps ! :)

Related

taking out sets of every 3 element from table (java)

I would like to take sets of every 3 elements from table, and then use them for some calculations. Let's say that my table is really big, e.g. 1000+ elements.
Tab elements are like like {x1,y1,z1,x2,y2,z2,...}.
I want to take the first three elements, do some calculations with them, take the next three elements, etc.
Here is my code so far:
double x=0;
double y=0;
double z=0;
for (int i =0; i<tab.length; i++)
x= (double)tab[i];
for (int j =0; j<tab.length; j+=2)
y= (double)tab[j];
for (int k =0; k<tab.length; k+=3)
z= (double)tab[k];
deathstar(x, y, z);
This is using only last 3 elements from tab and deathstar is printing calculation made only on last 3 elements. I was playing around with {}, but it didn't give me results that i wanted. Anyone have any solid idea how to take out every 3 elements from my table ? tab is defined outside of this code and is of type int[].
Thank You in advance for any thoughts about given issue.
Lose the increment part of the loop and increment after each element is gotten.
for (int i =0; i<tab.length;) {
X=(double)tab[i++];
Y=(double)tab[i++];
Z=(double)tab[i++];
//do something
}
This will grab three consecutive elements at a time and then do the calculation. Also checkS to make sure it won't go out of bounds.
double x=0;
double y=0;
double z=0;
int j = 1;
int k = 2;
for (int i =0; i<tab.length; i++)
{
if(i + j < tab.length && i + k < tab.length){
x= (double)tab[i];
y= (double)tab[i + j];
z= (double)tab[i + k];
deathstar(x, y, z);
}
}
You're missing a { after the last for, and so deathstar is only called after all loops finished. Better use { for every for-loop. You could find this easily using a Debugger.
Next, you will ask what's wrong with the logic and why yoou don't get the expected result, because now you would get deathstar(x1,y1,z1), deathstar(x1,y1,z2),.... Try the following (note: I'm assuming the length of tab is indeed a multiple of 3):
for(int i = 0; i < tab.length; i += 3) {
x = tab[i];
y = tab[i+1];
z = tab[i+2];
deathstar(x, y, z);
}
This way your code looks much cleaner.
for (int i =3; i<tab.length; i+=3){
tab[i-1]
tab[i-2]
tab[i-3]
}
maybe this approach will help you

Mathematical equivalent of multiple nested loops

When you have loop in the loop or nested loop, let`s say for-loop, regardless of the programming language(of course must be imperative)
for(int j = 1; j <= 100; j++){
for(int k = 1; k <= 200; k++){
\\body or terms
}
}
is the mathematical equivalent, when I want to sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on :
And the red-circled condition is unnecessary, right?
And the same applies for multiple nested loops?
The code you provided will run as you explained
sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on
However, the mathematical equivalent is without the condition marked in red.
The sigmas with the condition is equivalent to this code:
for(int j = 1; j <= 100; j++){
for(int k = 1; k < j; k++){
\\body or terms
}
}
Hope I helped.
Sigma stands for summation, which means that if you're dealing with sigma for a range, i=1,n, which is defined as x, then the result is going to be x * n (x + x + x + ... + x n times). Transcribed to pseudocode, it would be like this:
result = 0
for i=1,n:
result = result + x
So it doesn't really translate to a general for loop which is more about doing something a certain number or times or until a condition is met.
Often when you see mathematicians researching algorithms that relate directly to software fields, they use the more flexible functional notation and recursion a lot more than summation since such a functional notation actually translates a bit more directly to general loop computations than summation.

Java Prime calculator according to Sieve of Eratosthenes

I've stumbled on the following problem: I have a class to get and print all primes between 1 and N. The N is a parameter which you have to insert by yourself. When I insert 10000 for N, the code works and prints out all primes out from 2 to the closest prime to N.
When I insert 40000 the code still works. When I insert 50000 (or higher), the code gives an ArrayOutOfBoundsException. Why?
This is the code I use:
ArrayList<Integer> priemGetallen = priemGetallen(n);
for (Integer i : priemGetallen) {
System.out.println(i);
}
And uses
ArrayList<Integer> priemgetallen = new ArrayList<Integer>();
for(int i = 2; i < n; i++){
priemgetallen.add(i);
}
for (int i = 2; i < n; i++) {
for (int j = i; j * i <= n; j++) {
if((j*i) < priemgetallen.size()){
priemgetallen.remove(j*i);
}
}
}
return priemgetallen;
}
The point "priemgetallen.remove(j*i)" is where I receive the error.
I'd really appreciate it if someone can tell me why this doesn't work for all N's bigger then approx. 40000.
Thanks in advance!
The maximum value a Java int can hold is 2,147,483,647, so j * i is overflowing when i and j reach 46,341.
To extend the range, change the types of i, j and n to long.
See How does Java handle integer underflows and overflows and how would you check for it?
P.S. You'll also need to change priemgetallen into an array list of Long rather than Integer.

Avoiding rounding errors in a matrix calculation

I have the following very simple code that is supposed to iteratively change the values of a matrix (finalvals)until the row sums and column sums approach certain values (given by b1 and c) -
double[] rowsums = new double[3];
double[] colsums = new double[3];
Double[][] finalvals = {
{10320289.32d,15531663.71d,513718885.9d},
{5741307.806d,19279894.22d,254573082.9d},
{216919827.7d,229857986.8d,8769234962d}
};
Double[] b1 = {544169638d,273919997d,9217088452d};
Double[] c = {232981430d,264669549d,9537527108d};
for(int k = 0;k<1000;k++){
for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
rowsums[i] = rowsums[i] + finalvals[i][j];
}
}
for(int i = 0;i<3;i++) {
for(int j = 0;j<3;j++) {
finalvals[i][j] = b1[i] * finalvals[i][j] / rowsums[i];
}
}
for(int i = 0;i<3;i++) {
for(int j = 0;j<3;j++) {
colsums[j] = colsums[j] + finalvals[i][j];
}
}
for(int i = 0;i<3;i++) {
for(int j = 0;j<3;j++) {
finalvals[i][j] = c[j] * finalvals[i][j] / colsums[j];
}
}
}
for(int i = 0;i<3;i++) {
for(int j = 0;j<3;j++) {
System.out.print(finalvals[i][j] + " ");
}
System.out.print("\n");
}
However, the due to numerical leaks, the values of finalvals just become all zeros after a thousand iterations. Is there any way to plug these leaks?
Edit: A description of the algorithm - we want the matrix rows to sum to the arrays b1 and matrix columns to sum to array c. So, first distribute the first value of b1 among the first three rows of the matrix in proportion of the existing values and similarly for the other two rows. Then we do the same using the columns and the array c. We do this iteratively many times and we should finally get a matrix whose rows and columns sum appropriately.
If your algorithm gives excessive rounding errors, the solution should be to find a better algorithm, rather than to use higher precision numerics. This looks like a classic linear programming or simultaneous equation problem, for which there are tried and tested algorithms that work well. You need to sit down and study a bit on numerical methods.
Ok, I figured it out. The reason was actually not rounding errors at all, but my code was wrong. I should have been setting the rowsums and colsums to zero after every iteration of the k loop. Thanks for every ones help.

Java, drawing e cross

I'm trying to code a method which draws a cross in JAVA. (see the photo for an example).
Here is the example:
Few Questions:
how do I give an array the dimensions via parameter? It seems that Eclipse needs a number instead of variables for the array dimensions. I thought it is possible to give the method a parameter, how big the dimensions of the array should be.
Don't get the idea how to tell the loop which one of the array positions should be an X and which one not.
Here is my code idea so far...it does not really what it should do :) I took "1" instead of "X", so I can do it with an int array.
public void drawCross(int number){
int i,j;
int array[][]=new int[40][40];
for(j=1;j<=number;j++){
for(i=1;i<=number;i++){
if(array[i]==array[j]){
array[i][j]=1;
System.out.print(array[i][j]+" ");
}
}
System.out.print("\n");
}
}
Thank you in advance.
Pete
As this does not really seem homework, the solution
int[][] array = new int[number][number];
for (int i = 0; i < number; i++){
for (int j = 0; j < number; j++){
if (i == j || i == number - 1 - j) {
array[i][j] = 1;
}
System.out.print(array[i][j] + " ");
}
System.out.print("\n");
}
int[][] a is the conventional way. int a[][] is syntactic sugar for C programmers.
In math i normally is the row, and j the column, so switched the for-loops.
Arrays are indexed from 0.
The condition should say whether one is on one of both diagonals, so only concerns the indices i and j.
|| is OR, and && is AND (should you not already know).
As you see, the matrix array is not needed
So:
boolean isOnDiagonal = i == j || i == number - 1 - j;
System.out.print(isOnDiagonal ? "X " : ". "); // if-then-else operator.

Categories

Resources