首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >矩阵乘法和c的幂运算

矩阵乘法和c的幂运算
EN

Stack Overflow用户
提问于 2015-05-20 16:11:28
回答 1查看 49关注 0票数 0

我已经试过好几次了,但是从来没有成功过。有人能帮我找出我的代码出了什么问题吗?我的multi是对的。

代码语言:javascript
复制
uint32_t* matrix_mul(const uint32_t* matrix_a, const uint32_t* matrix_b) {

 uint32_t* result = new_matrix();

    /*
        to do

        1 2   1 0    1 2
        3 4 x 0 1 => 3 4

        1 2   5 6    19 22
        3 4 x 7 8 => 43 50
    */
    for(ssize_t y=0; y<g_height; y++){
        for(ssize_t x=0; x<g_width; x++){
            for(int i=0; i<g_width; i++)
                result[y*g_width + x]+=matrix_a[y*g_width + i]*matrix_b[i*g_width + x ];
        }
    }
    return result;
}

/**
 * Returns new matrix, powering the matrix to the exponent
 */
uint32_t* matrix_pow(const uint32_t* matrix, uint32_t exponent) {

    uint32_t* result = new_matrix();

    /*
        to do

        1 2        1 0
        3 4 ^ 0 => 0 1

        1 2        1 2
        3 4 ^ 1 => 3 4

        1 2        199 290
        3 4 ^ 4 => 435 634
    */
    uint32_t*tempresult=cloned(matrix);
    if(exponent==0){
        result=identity_matrix();
    }
    else if(exponent==1) {
            result=tempresult;
    } 
    else if(exponent==2){
        for(ssize_t y=0; y<g_height; y++){
            for(ssize_t x=0; x<g_width; x++){
                for(int i=0; i<g_width; i++)
                    result[y*g_width + x]+=matrix[y*g_width + i]*matrix[i*g_width + x ];
            }

        }
    }
else if(exponent>=3){
        for(ssize_t y=0; y<g_height; y++){
            for(ssize_t x=0; x<g_width; x++){
                for(int i=0; i<g_width; i++)
                       result[y*g_width + x]+=matrix[y*g_width + i]*matrix[i*g_width + x ];
            }

        }
        for(int j=1;j<=exponent-2;j++){
            for(ssize_t y=0; y<g_height; y++){
                for(ssize_t x=0; x<g_width; x++){
                    for(int i=0; i<g_width; i++)

                        result[y*g_width + x]+=result[y*g_width + i]*matrix[i*g_width + x ];

    return result;
}
EN

回答 1

Stack Overflow用户

发布于 2015-05-20 16:42:57

它会给出这样的东西:

代码语言:javascript
复制
uint32_t* matrix_pow(const uint32_t* matrix, uint32_t exponent) {

    uint32_t* tempresult=identity_matrix();
    ssize_t i;

    if (exponent == 0) return identity_matrix();
    for (i = 0; i < exponent; i++) tempresult = matrix_mul(tempresult, matrix);

    return tempresult;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30343893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档