【发布时间】:2016-12-30 08:54:36
【问题描述】:
此结构允许表示任意大小的矩阵,其中 M 是行数,N 是列数,data 是指向 M*N 类型的 double 类型值的指针,按行存储。
struct matrix {
size_t M, N;
double *data;
};
struct matrix *mat_directsum(const struct matrix *a, const struct matrix *b);
mat_directsum 函数接受两个指向数组的指针作为参数,并应返回直接和,在堆上动态分配。
A.M = 2
A.N = 3
A.data = (1, 1, 2, 0, 1, -3)
直接求和函数示例
我只需要一些关于如何设置函数的提示,只是想看看其他人如何使用这种类型的数组,因为我想到的唯一方法是具有许多循环的迭代方法,但是,这已经足够了长而巧妙,我想知道是否有更简单的方法来解决它。谢谢
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循环
【问题讨论】:
-
.... with many loops。嗯,两个嵌套的 for 循环就足够了。for(i=0; i<(a.M+b.M); ++i) { for(j=0; j<(a.N+b.N); ++j) { if (..... -
if 条件呢?
-
在
if部分,您将比较i和j与原始矩阵的大小,以决定您应该写入零还是应该从其中一个中取一个值输入矩阵。也许像if (i < a.M) { .... -
另一种方法可能是
calloc和一个for-循环,您在循环中使用了memcpy。我建议您尝试编写一些代码,然后用该代码更新您的问题(如果您有问题)。我很乐意帮忙,但我不会为你编写所有代码。 -
int n = c->M * c->M;- 其中之一应该是c->N