开发者

How to write mutiply matrix in C programming using pointers

Ok so I don't get how to writer this function it simply takes a scalar and multiplies it by the matrix, but I don't get how to call it on or anything.

I have created the Matrix:

MX* mxCreate(unsigned int height, unsigned int width) {
 开发者_StackOverflow   int i = 0;
    double** mxPtr;
    mxPtr = (double**)malloc(sizeof(double*) * height);
    ASSERT(mx, "Memory allocation failed");
    for(i = 0; i < height; i++){
        mxPtr[i] = (double *) malloc(sizeof(double) * width);
        ASSERT(mx[i], "Memory allocaiton failed");
    }
    MX *mx = malloc(sizeof(MX));
    ASSERT(mx, "Memory allocation failed");
    mx->w = width;
    mx->h = height;
    mx->m = mxPtr;
    return mx;
}

however how do I scalar multiply, here is what I have so far:

MX* mxScalar(const MX* mx, double scalar) {
    int i, j;
    s = scalar;
    for(i=0; i < h; i++)
    {
        for(j=0; j<w; i++)
        {
            mx[i][j] = s * m[i][j];
        }
    }
    return mx;
}

thanks


That looks OK as a basic structure (except that you have an i++ where you mean j++). You just need to access h, w and m as members of mx:

for(i = 0; i < mx->h; i++)
{
    for(j = 0; j < mx->w; j++)
    {
        mx->m[i][j] *= s;
    }
}

Your create routine really needs to set the every entry in the matrix to 0.0, though - memory returned by malloc could have any random junk in it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜