Intel® oneAPI Math Kernel Library
Ask questions and share information with other developers who use Intel® Math Kernel Library.
6981 Discussions

Using LAPACK_sgesv to solve a linear system with std::vector

Jamal_S_1
Beginner
492 Views

I am trying to use the LAPACK_sgesv function from the MKL to solve a linear system, which is part of a much larger problem. Now, as an example, this produces the correct answer:

int size = 4

float a[16] = {1, 1, 1 , 1, -2, -1, 1, 2, 4, 1, 1, 4, -8, -1, 1, 8}; // matrix A of Ax = B
float b[4] = { 0, 1, 0, 0 }; // vector B of Ax = B
int p[4] = { 0, 0, 0, 0 }; // array to store pivot indices


LAPACKE_sgesv(LAPACK_ROW_MAJOR, size, 1, a, size, p, b, 1);


for (auto& element : b)
	std::cout << "\n" << element;

The output is correct, and this behaves without errors. However, the main problem I have is that this function does not seem to work nicely with std::vectors:

int size = 4

std::vector<float> A = { 1, 1, 1, 1, -2, -1, 1, 2, 4, 1, 1, 4, -8, -1, 1, 8 };
std::vector<float> B = { 0, 1, 0, 0 };
std::vector<int> P = { 0, 0, 0, 0 };

LAPACKE_sgesv(LAPACK_ROW_MAJOR, size, 1, &A[0], size, &P[0], &B[0], 1);

for (auto& element : b)
	std::cout << "\n" << element;

The output I get is simply 0, 1, 0, 0, which is the unmodified output vector which the answer is suppose to be written to. The LAPACK returns zero, suggesting it executed successfully... Any ideas as to how to get it to work with vector? In my real use of this function in a larger calculation, I need to use resizeable contiguous containers, not arrays.

0 Kudos
1 Reply
Ying_H_Intel
Employee
492 Views

Hi Jamal,

I guess, there is a little typo in the std:: code 

for (auto& element : b)  ----> B
    std::cout << "\n" << element;
Then you will get the same result as the array code. 

Anyway, it is good question, so i add one more comment:  the key question here is whether the memory of  std:vector can be accessed continuously by  &A[0], &A[0]+1 ......  .  If yes, it is not problem to call MKL function with  LAPACKE_sgesv( &A[0], , &P[0], &B[0]); Otherwise, no. 

So you need to assure this point.  From the definition of std:vector, resizeable contiguous containers, it should be yes, right?

Best Regards,

Ying L_FA42.tmp_.PNG

0 Kudos
Reply