Convert Array to Tensor in C++

Hi,

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.

Thanks

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`)

Thanks

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.

2 Likes

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

2 Likes

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