1.示例源码
#include <stdio.h>
int min(int m, int n){ return m<n? m:n;}
void print_matrix(double* A, int m, int n, int lda)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
//printf("%7.4f ", A[i + j*lda]);
printf("%7.4f, ", A[i + j * lda]);
}
printf("; ...\n");
}
}
int main()
{
int m = 4; // Number of rows in the matrix
int n = 4; // Number of columns in the matrix
//double A[] = {1.0, 4.0, 2.0, 5.0, 3.0, 6.0}; // Input matrix
//double A[] = { 0.2029, 0.1386, 0.0747, 0.4070, 0.3765, 0.9046, 0.5039, 0.1746, 0.1999, 0.1830, 0.0428, 0.5782, 0.4996, 0.0351, 0.3829, 0.4178, 0.7555, 0.8836, 0.1705, 0.5099, 0.7483, 0.1933, 0.0904, 0.0653, 0.5536, 0.1145, 0.0588, 0.7315, 0.5379, 0.1212, 0.4357, 0.5835, 0.5118, 0.1740, 0.6601, 0.8425, 0.6992, 0.4402, 0.2148, 0.6044, 0.6756, 0.1013, 0.3293, 0.3598, 0.9349, 0.2801, 0.3233, 0.5857, 0.2380}; // Input matrix
double A[] = {
0.2029, 0.1386, 0.0747, 0.4070,
0.3765, 0.9046, 0.5039, 0.1746,
0.1999, 0.1830, 0.0428, 0.5782,
0.4996, 0.0351, 0.3829, 0.4178
}; // Input matrix
printf("A =\n");
print_matrix(A, m, n, m);
int lda = m; // Leading dimension of A
double tau[min(m,n)]; // Array to store elementary reflectors
int info; // Output variable for error info
int lwork = -1;
double* work = (double*)malloc(8);
// Call the LAPACK dgeqrf function for QR decomposition
dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info);
lwork = (int)work[0];
printf("lwork=%d\n", lwork);
work = (double*)malloc(lwork*sizeof(double)); // Workspace array
// Call the LAPACK dgeqrf function again with correct workspace
dgeqrf_(&m, &n, A, &lda, tau, work, &lwork, &info);
if (info == 0) {
printf("QR decomposition successful!\n");
// Print the decomposed matrix A
printf("Decomposed matrix A:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%8.5f ", A[i + j*m]);
}
printf("\n");
}
} else {
printf("QR decomposition failed!\n");
}
printf("\nTAU=\n");
for(int i=0; i<min(m,n); i++)
{
printf(" %8.5f ", tau[i]);
}
printf("\n\n");
return 0;
}
2. Makefile
STATIC_LIB = ../../liblapack.a ../../librefblas.a
LD_FLAGS = -lgfortran -lm
EXE := dgeqrf_
all: $(EXE)
%: %.c
gcc -g $< $(STATIC_LIB) $(LD_FLAGS) -o $@
.PHONY: clean
clean:
${RM} $(EXE) *.o
3. 运行