John777
John777

Reputation: 3

Good way to cast `dlib::matrix<T>` into `dlib::matrix<S>`?

What is a good way to cast dlib::matrix<T> into dlib::matrix<S>? For example, dlib::matrix<float> into dlib::matrix<std::complex<float> >?

Edit: I am looking for something more efficient than this:

template <class T> void toComplex(const dlib::matrix<T>& matr, dlib::matrix<std::complex<T> >& res) {
  res = dlib::zeros_matrix<std::complex<T> >(matr.nr(), matr.nc());
  for (unsigned i = 0; i < matr.nr(); ++i) {
    for (unsigned j = 0; j < matr.nc(); ++j) {
      res(i,j) = std::complex<T>(matr(i,j), 0);
    }
  }
}

Edit2: Cleaner, but not much faster solution (thanks, @idclev_463035818, for suggesting):

template <class T> void toComplex(const dlib::matrix<T>& matr, dlib::matrix<std::complex<T> >& res) {
  res.set_size(matr.nr(), matr.nc());
  std::copy(matr.begin(), matr.end(), res.begin());
}

Upvotes: 0

Views: 152

Answers (2)

Davis King
Davis King

Reputation: 4791

You want to call complex_matrix(your_real_matrix). See http://dlib.net/dlib/matrix/matrix_math_functions_abstract.h.html#complex_matrix. There are a variety of similar casting routines.

Upvotes: 0

Surt
Surt

Reputation: 16109

What a cast would at least require that

sizeof(float) == sizeof(std::complex<float>)

Which is not usually the case as the imaginary part is not placed in imaginary memory.

You might check if

<some code to resize res to matr without initializing anything>
std::copy(matr.cbegin(), matr.cend(), res.begin());

is faster.

Upvotes: 1

Related Questions