Unrestricted conversion from Array to TypedArray<std::complex<double>>?

Viewed 160

Tried many things, just cannot get it to work when writing a mex-function.

I have an input from MATLAB which I pass to a method as const matlab::data::Array. This array may contain complex data, sometimes it's only real. So the most straightforward approach should be, in my naive thoughts, that I can simply convert the Array to a TypedArray<std::complex<double>> and I get full complex values if the array contains complex values, and I get complex values with imag=0 if the array contains only real values. It seems to be impossible... This last conversion is not accepted in any case, and MATLAB even simply crashes on trying to cast single elements from a real-valued Array to std::complex<double>.

Anybody a solution how to get a TypedArray<std::complex<double>> in all cases so I can use that in C++ code?

1 Answers

Story of my life, trying for hours and after posting here I find something that works within half an hour... Following code seems to do the job:

void prepareObject(const matlab::data::Array& corners, const matlab::data::Array& facets)
{
    size_t N_facet_rows    = facets.getDimensions()[0];
    size_t N_facet_columns = facets.getDimensions()[1];
    matlab::data::TypedArray<std::complex<double>> complex_facets = arrayFactory.createArray<std::complex<double>>(facets.getDimensions());
    
    // Convert the facets to a complex-valued array.
    
    if (facets.getType() == ArrayType::DOUBLE) {
        std::complex<double> v;
        
        // Input is DOUBLE, so for each value init a complex<double> and store that in the complex array.
        
        v.imag(0);
        for (int i_r = 0; i_r < N_facet_rows; i_r++) {
            for (int i_c = 0; i_c < N_facet_columns; i_c++) {
                v.real(facets[i_r][i_c]);
                complex_facets[i_r][i_c] = v;
            }
        }
    }
    else {
        
        // Input is COMPLEX_DOUBLE, so simply copy all values.
        
        for (int i_r = 0; i_r < N_facet_rows; i_r++) {
            for (int i_c = 0; i_c < N_facet_columns; i_c++) {
                complex_facets[i_r][i_c] = (std::complex<double>) facets[i_r][i_c];
            }
        }
    }
    
Related