마지막으로 몇 가지 검색 및 시도를 한 후에는이 작업을 수행하고 스파 스 매트릭스를 읽는 방법을 발견했습니다. 내 작업은 실제로 비교적 간단하므로 더 복잡하고 좀 더 일반적인 목적을 위해이 조잡한 방법이 효과적인지 아닌지를 알지 못합니다.
기본적인 아이디어는 부스트의 희소 행렬에있는 모든 0이 아닌 요소를 const_iterator (자세한 내용은 link 참조)를 통해 반복하여 ofstream
에 쓰는 것입니다. 그리고 ifstream
에서 읽으면, 나는 가난한 사람의 방법을 사용하고 있습니다 : 반복적으로 쓰기 형식에 따라 읽고 스파 스 매트릭스에 삽입하십시오. 여기에 내 코드 내 테스트하기위한 목적 :
#include <iostream>
#include <fstream>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/io.hpp>
int main(int argc, char** argv)
{
using std::cerr;
using std::cout;
using std::endl;
using namespace boost::numeric::ublas;
typedef compressed_matrix<float, row_major> cMatrix;
const size_t size = 5;
const size_t rowInd[5] = { 0, 0, 1, 2, 4 };
const size_t colInd[5] = { 0, 2, 0, 4, 4 };
cMatrix sparseMat(size,size);
for (size_t i=0; i<size; ++i)
sparseMat.insert_element(rowInd[i], colInd[i], 1.0);
cout << sparseMat << endl;
// Try writing to file
std::ofstream ofsDat("temp.dat", std::ios::out | std::ios::binary);
for(cMatrix::const_iterator1 rowIter = sparseMat.begin1(); rowIter != sparseMat.end1(); ++rowIter) {
for(cMatrix::const_iterator2 colIter = rowIter.begin(); colIter != rowIter.end(); ++colIter) {
ofsDat << " " << colIter.index1() << " " << colIter.index2() << " " << *colIter;
} // end for colIter
} // end for rowIter
ofsDat.close();
cout << "Writing ended, starting to read" << endl;
// Try reading the file
cMatrix sparseMat_2(size, size);
std::ifstream ifsDat("temp.dat", std::ios::in | std::ios::binary);
size_t rowTemp, colTemp;
float valTemp;
while(!ifsDat.eof()) {
ifsDat >> rowTemp >> colTemp >> valTemp;
cout << "row " << rowTemp << " column " << colTemp << " value " << valTemp << endl;
sparseMat_2.insert_element(rowTemp, colTemp, valTemp);
}
cout << sparseMat_2 << endl;
return 0;
}
내가 구분 기호로 데이터 사이에 공백을 추가, 난이 할 수있는 더 좋은, 또는 표준 방법이 있는지 몰라? 모든 의견을 부탁드립니다!
답장을 보내 주셔서 감사합니다. 나는 이미 "메모리의 청크를 직접 관리하는 방식으로이"읽기 - 쓰기 "를 할 수 있다고 생각하는 나의 오래된 생각을 포기했다. 그래서 나는 "요소별로 읽기/쓰기"를 할 생각을 해왔다. 당신의 본보기가 바로 이것입니다. 내 유일한 관심사는 M이 0 인 희소 2D 행렬 (NxN)의 경우 두 개의 루프를 수행하는 복잡성이 N^2이지만이 쓰기 작업은 실제로는 0이 아닌 요소에 대한 M 개의 액세스 만 필요로합니다. 그렇다면 0이 아닌 요소를 모두 효율적으로 반복 할 수있는 방법이 있습니까? – YangLou
이 링크가 발견되었습니다. [link] (http://stackoverflow.com/questions/1795658/looping-over-the-non-zero-elements-of-a-ublas-sparse-matrix) 0이 아닌 모든 원소를 반복하여 0이 아닌 모든 원소를 반복하려면? 아니면 여기에 뭔가 빠졌나요? – YangLou
안녕하세요 @ YangLou. 프로파일 러를 점검하지는 않았지만, 파일을 작성하고 0을 채우기 때문에 데이터를 얻는 것이 병목 목에 중요하지 않습니다. 스파 스 매트릭스를 사용하면 매트릭스에서 더 빠르게 계산할 수 있습니다. – lakeweb