【发布时间】:2021-12-13 04:08:48
【问题描述】:
我想对从文件中读取的数据执行一些数学运算,例如加/减、均值等。数据是二维的,看起来像这样: 所以现在例如我想从第 3 行或第 4 行中减去第一行,在 python 中使用索引非常简单,但我不知道如何在 c++ 中做。 这是我正在使用的代码。
#include <boost/multi_array.hpp>
#include <boost/timer/timer.hpp>
#include <boost/range/irange.hpp>
#include <h5xx/h5xx.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
using array_2d_t = boost::multi_array<float, 2>;
template <typename T>
void print_array(T const& array)
{
for (auto const& row : array)
{ for (auto v : row)
printf("%10f ", v);
printf("\n"); //prints a new line similar t0 \n
}
std::cout << "\n End of file" << std::endl;
}
array_2d_t read_frame(std::string const& filename, unsigned frame_no) {
//h5xx::file xaa("../../data/xaa.h5", h5xx::file::mode::in);
h5xx::file xaa(filename, h5xx::file::mode::in);
h5xx::group g(xaa, "particles/lipids/box/positions");
h5xx::dataset ds(g, "value");
// determine dataset shape: frames, particle count, space dimension
auto ds_shape = h5xx::dataspace(ds).extents<3>();
array_2d_t arr(boost::extents[ds_shape[1]][ds_shape[2]]);
std::vector<hsize_t> offsets{frame_no, 0, 0};
std::vector<hsize_t> counts{1, arr.shape()[0], arr.shape()[1]};
//std::vector<hsize_t> strid{1, arr.shape()[0], arr.shape()[1]};
// slice ohne stride:
h5xx::slice slice(offsets, counts);
h5xx::read_dataset(ds, arr, slice);
return arr;
}
int main(int argc, char const* argv[])
{
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " input.h5" << std::endl;
return -1;
}
std::string filename(argv[1]);
print_array(read_frame(filename, 1));
return 0;
}
read_frame 函数接受参数文件名和 frame_no。该文件被分成帧,每个帧包含 (11214) 行,但在这里了解并不重要。所以 read_frame 返回每一帧的二维数据。在 main() 函数中,我可以打印每一帧的数据,但现在假设我想从第二帧中减去第一帧,我该怎么做? 有谁知道吗
【问题讨论】:
-
你能展示一下 Python 吗?这将使您清楚/什么/您想要实现,而不是您认为它应该如何工作
-
@sehe 准确地说,我想取前 4 帧的平均值,然后从第五帧中减去。但首先我只是想了解一下这些框架上的基本操作。
-
那是……不是我要求的。但你知道,我会添加一些