Convert Array to Tensor in C++


I have to give a matrix as input to my network, which is a standard C++ 2d array, and I can’t find a method to transform my data to a tensor. I hope someone can help me.


1 Like

How did you implement your matrix? Similar question here, is there a way to do

#include <torch/torch.h>
torch::Tensor a = torch::tensor(~matrix`)


it’s read from a .txt file the matrix is build this way:

float **matrix = new float *[rows];

for (size_t row = 0; row != rows; row++) {
matrix[row] = new float[cols];

Found the solution. You can use the torch::from_blob() function to read an array and turn it to a tensor. Apparently you also need to call .clone() because of some memory issue.


I think the clone() call is only necessary, if you don’t want to keep the passed array alive, which would invalidate the data?


I did not mention here that everything is processed with cuda, i had to insert clone() , otherwise i just got an error.