简体   繁体   English

使用 C++ 中的指针将两个矩阵相乘

[英]Multiplying two matrices using pointers in C++

I want to multiply matrices using pointers, which I have seen over the internet.我想使用我在互联网上看到的指针来乘以矩阵。 But what I have not seen is how to do that with just two for loops.但我没有看到的是如何只用两个 for 循环来做到这一点。 All solutions I've seen were consisting of three for loops.我见过的所有解决方案都由三个 for 循环组成。 I have opened another question about this but it got closed due to duplication but my question wasn't answered there.我已经对此提出了另一个问题,但由于重复而关闭,但我的问题没有在那里得到回答。

Maybe I should have given an example of my code:也许我应该给出我的代码示例:

for(i = 0; i < size; ++i)
    for(j = 0; j < size; ++j)
        {
            *((*PRODUCT)+i) += *((*A)+j) * *((*B)+size*j+i);
        }

This is what I've done.这就是我所做的。 It uses pointers to reach elements of the matrix.它使用指针来访问矩阵的元素。 But it doesn't work...但它不起作用...

Here is a naive matrix multiplication using pointers and two for loops.这是一个使用指针和两个for循环的简单矩阵乘法。 Note that it does the same amount of work as a typical three loop implementation.请注意,它的工作量与典型的三循环实现相同。 It just combines the two outer loops as one and calculates the i and j indexes.它只是将两个外部循环组合为一个并计算ij索引。

void multiply(const float *A, const float *B, float *result, int N) // square N*N matrixes
{
    // combine two outer loops into one
    for (int n = 0, size = N * N; n < size; ++n) {

        // compute i and j indexes
        int i = n / N;
        int j = n % N;

        // inner loop
        float temp = 0;
        for (int k = 0; k < N; ++k) {
            temp += A[i * N + k] * B[k * N + j];
        }
        result[i * N + j] = temp;
    }
}

int main()
{
    int N = 42;
    float *A = new float[N * N];
    float *B = new float[N * N];
    float *C = new float[N * N];

    // give A and B some values...

    multiply(A, B, C, N);
}

I used array notation because A[i * N + k] is easier to read than *(A + i * N + k)我使用数组表示法是因为A[i * N + k]*(A + i * N + k)更容易阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM