How do I do vector product by matrix and between matrices?

Asked

Viewed 1,766 times

1

I can’t think of a for that performs this multiplication, because the number of columns of the first matrix has to be equal to the number of rows of the second matrix...

  • Look for some of your analytical geometry classes or linear algebra. There you have done these calculations. Try to simulate in hand what you have done in the past. Also check if your data structure is adequate; mathematically puma matrix has two valued dimensions and also has its internal values, in the field of the matrix

1 answer

3


Matrix Product

Before making any code you need to know how the product works between matrices.

Considering two matrices A and B, the matrix product is made by multiplying each value of a line of A for each value in a column of B, and adding these partial all. This process is thus applied to all lines of A and columns of B.

See an illustration of this process:

inserir a descrição da imagem aqui

Considering the matrices of the illustration A large 4x2 and B 2x3, the resulting matrix, which I will call R, will be the size 4x3. Here you see that R must have the number of rows of the first matrix and the number of columns of the second matrix.

In this matrix R the first house R11 would then be defined by:

R11 = A11*B11 + A12*B21;

The second house R12, which is highlighted in the figure in red, would be calculated as:

R12 = A11*B12 + A12*B22;

And so on for the remaining boxes.

Calculation in C

Now that we know how the product works between matrices we can move on to the implementation. Indicated a for for solving the problem and in fact will be necessary 3 for it. The first 2 for run through each cell of the resulting matrix and the 3 runs A and B to calculate.

Implementation:

int A[2][2] = {{1,2},{3,4}};
int B[2][2] = {{2,0},{1,2}};
int R[2][2] = {0};

int i,j,k;

for(i=0; i<2; i++){
    for(j=0; j<2; j++){
        for(k=0; k<2; k++){
            R[i][j] += A[i][k] * B[k][j];
        }
    }
}

See the example in Ideone

Note: The product between vector and matrix is the same thing as the product between matrix and matrix, as a vector is a particular case of a matrix with only a row or column.

Recommended reading:

Browser other questions tagged

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