0

My goal is to initialize a size m x 3 matrix and fill its rows with 1 x 3 vectors (arrays I mean) obtained from a for loop. I'm not sure if I want to return the matrix (via pointer) yet or not. But I'm really rusty with C++ (wasn't very great to begin with). Any advice would be great. Here's my code:

#include "rk4.h"
#include <iostream>

using std::cout;
using std::endl;

double * rk4(double finalTime, double deltaTime, double Y0[])
{
    double h = 0.0009765625;    /// 1/2^10
    double t0 = 0;
    int rows = finalTime/h;
    double * Y = new double[M][3]; 

    for(int i = 0; i < 3; i++)
    {
        Y[0][i] = Y0[i];
    }

    cout << M << endl;

    for(double t = t0; t <= finalTime; t+= h)
    {
       // Insert row into Y
    }

    return Y;
}

I'm getting an error that says cannot convert double(*)[3] to double* in initialization. Also I'm expecting to use huge arrays for these computations so any other advice would be great.

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
Zduff
  • 171
  • 11

2 Answers2

2

The following is not valid C++. A compiler should let you know.

double * Y = new double[M][3]; 

Use a std::vector of std::array instead.

std::vector<std::array<double, 3>> Y(M);

You will need to change the return type too.

std::vector<std::array<double, 3>> rk4(...) { ... }
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

If you have Boost, the simplest way to declare a matrix is to use boost::matrix

#include <iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main () {
    using namespace boost::numeric::ublas;
    matrix<double> m (3, 3);
    for (unsigned i = 0; i < m.size1 (); ++ i)
        for (unsigned j = 0; j < m.size2 (); ++ j)
            m (i, j) = 3 * i + j;
    std::cout << m << std::endl;
}

Boost also has multi_array, but it is known to have performance issues in some implementations. Check your performance if you are considering adopting boost::multi_array

Boost::multi_array performance question

The Vivandiere
  • 3,059
  • 3
  • 28
  • 50