Search code examples
c++loopsfor-loopnested-loopsfunction-definition

error in c++ matrix*vector multiplication


I need a function that multiply a matrix and a vector (Matrix*vector)

It takes in a matrix A and a vector B, with int describing the dimensions. Somehow it isn't running correctly. Any help??

void Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
{

    if (ACols !=BRows)

    {

        return;
    }
    
    for (int i = 0; i < ACols; i++)
    {
        res[i] = 0;
        for (int j = 0; j < BRows; j++)
        {
            res[i] += A[i][j]*B[j];
        }
    }
}

Solution

  • It seems you mean

    for (int i = 0; i < ARows; i++)
    {
        res[i] = 0;
        for (int j = 0; j < ACols; j++)
        {
            res[i] += A[i][j]*B[j];
        }
    }
    

    It would be better if the function returns a boolean value that signals whether the function execution was successful for example

    bool Multiply(double *res, double **A, double *B, int ARows, int ACols, int BRows)
    {    
       bool success = ACols == BRows;
    
        if ( success )
        {
            for (int i = 0; i < ARows; i++)
            {
                res[i] = 0;
                for (int j = 0; j < ACols; j++)
                {
                   res[i] += A[i][j]*B[j];
                }
            }
        }
    
        return success;
    } 
    

    Instead of the manually written loops you could use the standard algorithm std::inner_product declared in the header <numeric>.