Vector multiplication A and B resulting in matrix C

Asked

Viewed 690 times

0

I have an exercise in Java here to solve but I could not understand exactly what I need to do, if anyone can give me a better explanation thank you! This is what I need to do:

Given the vectors A = [1,2,3,4,5] and B = [1,2,3,4,5], create algorithms to generate a matrix C of the multiplication of the elements of A by the elements of B. Note that

C[1,1] <- A[1,1] * B[1,1]
C[1,2] <- A[1,1] * B[1,2]
C[1,3] <- A[1,1] * B[1,3] 
...
  • What number would B[1,2] ?

  • The number 2 in the case

1 answer

4


You need to use two interleaved loops to do this type of operation: the outermost one will fill rows of the resulting matrix, while moving the items of the first array(Veta), the second one will fill columns of the resulting matrix, while moving items of the second array(vetB):

The code stays that way:

int[] vetA = {1,2,3,4,5};
int[] vetB = {1,2,3,4,5};
int[][] mat =  new int[5][5];

for(int i = 0; i < vetA.length;i++){
    for(int j = 0; j < vetB.length; j++){
        mat[i][j] = vetA[i] * vetB[j];
    }
}

for(int i = 0; i < mat[0].length; i++){
    for(int j = 0; j < mat.length;j++ ){
        System.out.print(mat[i][j] + " ");
    }
    System.out.println();
}

Upshot:

1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25

See it working on ideone: https://ideone.com/Qp7iYG

Note that as we have a multiplication that will result in a square matrix, you can use the same combination to display on the screen.

  • That’s right! I was getting close but some things were missing thank you haha!

  • 1

    @Leonardo dispose :)

  • 2

    @Leonardo next shows you what you’ve already done, in case Diego isn’t around, it’s easier to help :D

  • @diegofm A doubt at display time, pq vc used mat[0]. length in the first for and mat.length in the second?

  • 1

    @Leonardo because mat[0]. length returns the total equivalent of "columns" of the matrix, and mat.length returns the total equivalent of "rows". Note that this loop works correctly only on quadratic matrices(totalLines = totalColumns)

  • Ahh understood, thank you very much!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.