C 语言中从 2D 数组到 2x2 矩阵

问题描述 投票:0回答:1

我正在尝试从两个包含 C 中的值的 2D 数组创建一个 2x2 矩阵。要生成的矩阵名为重叠,是一个 2x2 矩阵,其元素是每个 D 和 A 数组的函数。 我编写了以下代码及其输出如下所示。 我不知道我做错了什么,并且想知道读到这篇文章的人是否可以帮助一个被误导的新 C 学习者。 附:我知道我可以显式地编写每个元素,然后将它们放入矩阵中,而无需使用数组;但是,我计划使用这个框架作为自动化计算代码的基础,以获得更大的输入。

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define BASISFUN 2
#define PI 3.14159265358979323846
void overlaps(double overlap[][2], double d[][2], double a[][2]) {
  printf("\nThe Overlap Matrix is\n");
  for (int i = 0; i < BASISFUN; i++) {
    for (int j = 0; j < BASISFUN; j++) {
      overlap[i][j] = 0.0;
      if (i == j && i == 0) {
        overlap[0][0] =
            pow(d[0][0], 2.0) * pow((PI / (a[0][0] + a[0][0])), 1.5);
      } else if (i == j && i == 1) {
        overlap[1][1] =
            pow(d[1][1], 2.0) * pow((PI / (a[1][1] + a[1][1])), 1.5);
      } else if (i != j && i == 1) {
        overlap[1][0] =
            pow(d[1][0], 2.0) * pow((PI / (a[1][0] + a[1][0])), 1.5);
      } else {
        overlap[0][1] =
            pow(d[0][1], 2.0) * pow((PI / (a[0][1] + a[0][1])), 1.5);
      }
      printf("%.4f\t", overlap[i][j]);
    }
    printf("\n");
  }
}
int main() {
  double A1 = 0.532149;
  double A2 = 4.097728;
  double D1 = 0.82559;
  double D2 = 0.28317;
  double a[1][2] = {A1, A2};
  double d[1][2] = {D1, D2};
  double overlap[2][2];
  overlaps(overlap, d, a);
  return 0;
}

输出: 轨道系数矩阵为

3.4567  0.0190  
3.6998  44.0676 

但是,使用Matlab时,乘积应该是这样的,这是100%正确的:

3.4567    0.1307
0.1307    0.0190
arrays c math matrix
1个回答
0
投票

a
d
尺寸和
overlap
的计算不正确:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define BASISFUN 2
#define PI 3.14159265358979323846

void overlaps(double overlap[][2], double d[][2], double a[][2]) {
  printf("The Overlap Matrix is:\n");

  overlap[0][0] = pow(d[0][0], 2.0) * pow((PI / (a[0][0] + a[0][0])), 1.5);
  overlap[0][1] = pow(d[0][1], 2.0) * pow((PI / (a[0][1] + a[0][1])), 1.5);
  overlap[1][0] = pow(d[1][0], 2.0) * pow((PI / (a[0][0] + a[0][0])), 1.5);
  overlap[1][1] = pow(d[1][1], 2.0) * pow((PI / (a[0][1] + a[0][1])), 1.5);

  for (int i = 0; i < BASISFUN; i++) {
    for (int j = 0; j < BASISFUN; j++) {
      printf("%.8f\t", overlap[i][j]);
    }
    printf("\n");
  }
}

int main() {
  double A1 = 0.532149, A2 = 4.097728, D1 = 0.82559, D2 = 0.28317;

  double a[2][2] = {{A1, A2}, {A1, A2}};
  double d[2][2] = {{D1, D2}, {D1, D2}};

  double overlap[2][2];
  overlaps(overlap, d, a);

  return 0;
}

打印

The Overlap Matrix is:
3.45667690  0.01903091  
3.45667690  0.01903091  

© www.soinside.com 2019 - 2024. All rights reserved.