Hi everyone,
Having correlated responses in statistical analysis is common. For example, in spatial analysis, we customarily use Gaussian Process to capture the spatial pattern. Some modeling methods approximate the original likelihood by a product of conditionally independent processes, whose performance will depend on the order of the observations. The model I am working on has the same issue. Since it requires sorted locations, I want to write a function to order the coordinates base on one dimension, and sort the outcome and the design matrix according to the sorted locations.
My plan is to get the original index of the sorted locations, and then use the index to sort the response and the predictors. But when I tried to use "sort_indices_asc"in stan math library to sort the input coords:
vector<int> sortind = stan::math::sort_indices_asc(coords.col(0));
(here “coords” is Eigen::Matrix <double, N, 2>) I got an error message:
error: no type named 'type' in 'stan::math::index_type<Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, -1, 1, true> >'
.
So here are my questions:
How to use the existing functions to
- get the index for sort by the first column of a matrix?
- sort the target matrix by the index?
Besides, I wrote two functions for the questions above. It will be great if I can use the functions in Stan Math to replace the function I wrote.
get_sort_ind.hpp
#ifndef GET_SORT_IND_HPP
#define GET_SORT_IND_HPP
#include <fstream>
#include <iostream>
#include <vector>
#include <numeric>
using std::vector;
using std::iota;
template <typename T>
void
get_sort_ind(const T& coords, vector<int>& idx){
idx.resize(coords.size());
std::iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(),
[&coords](size_t i1, size_t i2) {return coords[i1] < coords[i2];});
return;
}
#endif
sort_data_by_ind.hpp
#ifndef SORT_DATA_BY_IND_HPP
#define SORT_DATA_BY_IND_HPP
#include <fstream>
#include <iostream>
#include <vector>
#include <Eigen/Dense>
using std::vector;
using Eigen::Matrix;
using Eigen::Dynamic;
template <typename T, typename size_t>
Matrix<T, Dynamic, Dynamic>
sort_data_by_ind(const Matrix<T, Dynamic, Dynamic> data,
const vector<size_t> sortind){
Matrix<T, -1, -1> sorted_data;
sorted_data.resize(data.rows(), data.cols());
for (int i = 0; i < data.rows(); i++ ){
for (int j = 0; j < data.cols(); j++){
sorted_data(i, j) = data(sortind[i], j);
}
}
return sorted_data;
}
#endif
Thanks,
Lu Zhang