gpt4 book ai didi

c - 矩阵函数的直和

转载 作者:行者123 更新时间:2023-11-30 20:21:48 26 4
gpt4 key购买 nike

该结构允许表示任意大小的矩阵,其中 M 是行数,N 是列数,data 是指向按行存储的 double 型 M*N 值的指针。

struct matrix {
size_t M, N;
double *data;
};


struct matrix *mat_directsum(const struct matrix *a, const struct matrix *b);

函数ma​​t_directsum接受两个指向数组的指针作为参数,并应返回在堆上动态分配的直接和。

示例:
enter image description here

A.M = 2
A.N = 3
A.data = (1, 1, 2, 0, 1, -3)

直接求和函数示例

enter image description here

我只需要一些关于如何设置函数的技巧,只是为了看看其他人如何处理这种类型的数组,因为想到的唯一方法是具有许多循环的迭代方法,但是,这已经足够了又长又巧妙,我想知道是否有更简单的方法来解决它。谢谢

ps。(内存分配当然不是问题)

编辑我是这样解决的:

struct matrix *mat_directsum(const struct matrix *a, const struct matrix *b) {
struct matrix *c = malloc(sizeof(struct matrix));
c->M = a->M + b->M;
c->N = a->N + b->N;
int n = c->M * c->M;
double *dati = calloc(n, sizeof(double));

int t = 0;//index new array
int y = 0;//index first mat
int z = 0;//index second mat
for (int i = 0; i < c->N; i++) {
if (i < a->N) {//first mat
for (int j = 0; j < c->M; j++) {
if (j < a->M) {
dati[t] = a->data[y];
y++;
}
t++;
}
} else {//second mat
for (int j = 0; j < c->M; j++) {
if (j >= a->M) {
dati[t] = b->data[z];
z++;
}
t++;
}
}
}
c->data = dati;
return c;
}

我不知道如何做到这一点,只有一个 for 循环

最佳答案

//macro which will point to an element indexed at [xe][ye]
#define ELEMENT(data,rows,columns,xe,ye) (data+((xe)*(columns)+(ye)))

struct matrix
{
size_t M, N;
double *data;
};


//won't mind changing the return type from "struct matrix*" to "struct matrix"
struct matrix mat_directsum(const struct matrix *a, const struct matrix *b)
{
int x;
struct matrix res;
res.M = a->M + b->M;
res.N = a->N + b->N;

//using calloc will set the memory to zero i.e all the bytes will be set to zero.
res.data = (double*)calloc(res.M * res.N, sizeof(double));
if(res.data == NULL)
{
return res;
}

for(x = 0; x < a->M; ++x)
{
memcpy(ELEMENT(res.data, res.M, res.N, x, 0), ELEMENT(a->data, a->M, a->N, x, 0), a->N * sizeof(double));
}
for(x = 0; x < b->M; ++x)
{
//note the offset by [a->M][a->N] while accessing elements of res.
memcpy(ELEMENT(res.data, res.M, res.N, x + a->M, a->N), ELEMENT(b->data, b->M, b->N, x, 0), b->N * sizeof(double));
}

return res;
}


struct matrix res = mat_directsum(&a, &b);
if(res.data != NULL)
{
free(res.data);
}

关于c - 矩阵函数的直和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com