0

I have to add two 2D arrays. I wonder if there is a faster way to do it than this:

    double** x=new double*[1000];
    for(int i=0;i<1000;i++) {

            x[i]=new double[100];
    }
     //x y z are all the same dimension

    for(int i=0;i<1000;i++) {
       for(int j=0;j<100;j++) x[i][j]=y[i][j]/2.0+z[i][j]/2.0;
       }
7
  • A minimal reproducible example would be good. Commented Aug 25, 2019 at 4:06
  • 3
    double ** x=new double*[1000]; doesn't allocate a 2D array, it allocates a 1D array consisting of 1000 double * pointers. Perhaps you intended double x[1000][100]; instead? Commented Aug 25, 2019 at 4:06
  • IPP might be able to do it faster, but I doubt you really want to add it as a dependency. It's mostly for signal processing., I believe. Commented Aug 25, 2019 at 4:08
  • x[i][j]=y[i][j]/2.0+z[i][j]/2.0; invokes Undefined Behavior as x[i] is an uninitialized pointer to nowhere. You would need for(int i=0;i<1000;i++) { x[i] = new double[100]; for(int j=0;j<100;j++) ... Commented Aug 25, 2019 at 4:31
  • 4
    Get your code correct first, worry about fast later. Commented Aug 25, 2019 at 4:45

1 Answer 1

1

For fast an easy operations on matrices, you may consider to use std::valarray. This (not so popular) container has been desigend for exactly that purpose.

I admit that they are not so easy to understand, especially not the slice or gslice part, but if you learned how to use them, then they are very powerful.

And on some machines, they have native support and are extremely fast.

Here is one (of many) possible examples:

#include <iostream>
#include <valarray>
#include <numeric>

constexpr size_t NumberOfRows = 10;
constexpr size_t NumberOfColumns = 20;
constexpr size_t MatrixSize = NumberOfRows * NumberOfColumns;

int main(void)
{
    // Define some valarrays
    std::valarray<double> y(MatrixSize);
    std::valarray<double> z(MatrixSize);

    // And fill them with some demo values
    std::iota(std::begin(y), std::end(y), 200);
    std::iota(std::begin(z), std::end(z), 400);

    // Perform mathematical operations on all elements of array
    y /= 2.0;
    z /= 2.0;
    // Simply add 2 arrays to a new one
    std::valarray<double> x =  y + z;

    // Display result
    for (size_t i = 0; i < MatrixSize; ++i) 
        std::cout << (((i % NumberOfColumns) == 0) ? "\n" : " " ) << x[i];

    return 0;
}

Sign up to request clarification or add additional context in comments.

2 Comments

valarray is designed for efficiency, but few implementations actually optimize it at all ...
Yes, true. And only on some machines, they have native support and are extremely fast. And the future of std::valarray is also not so clear to me. Sad story . . .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.