根据下面提到的pdf链接,我需要计算给定矩阵'A'和
的矩阵'x'
使用后向替换的上三角矩阵的矩阵'b'。
链接:http://www.mathcs.emory.edu/~haber/math315/chap3.pdf
实际上我只需要使用1维数组。我也为它开发了逻辑并尝试了
编译它,但实际上它没有“表达式”和“初始化”的错误
| 1 2 3 | | X0 | | B0 |
| 0 4 5 | x | x1 | = | b1 |
| 0 0 6 | | X2 | | B2 |
公式:
1)6 * x2 = b2
2)4 * x1 + 5 * x2 = b1
3)1 * x0 + 2 * x1 + 3 * x3 = b0
This is my code:
//here: 's' is size of matrix eg: for 3x3 it is 3
//x[] i need to get the result
//b[] it is to be multiplied with cm to get
//cm[] is the matrix which will be multiplied with b[] to get x[]
for(int p=s-1; p>0; p--)
{
if(p==s-1)
{
x[p] = b[p]/cm[s*s]; // computing x2
}
else
{
for(int j=0; int k=s-p; j<s-i; k>0; j++; k--)
{
c[p]+ = cm[s*p - j]*x[p+k];
}
}
x[p] = (b[p] - c[p])/cm[s*p-(s-i)];
}
Errors:
1) variable 'x' may not be initialized
2) variable 'c' may not be initialized
3) expression for(int j=10; intk=s-p;j<s-i;k>0;j++;k--) has no effect
4) expected a ")" in point 3.
5) expected an expression in line c[p]+ = cm[s*p - j]*x[p+k];
6) variable 'x' was set but never used
Please help me how to solve these errors?
Also let me know is my logic correct?
答案 0 :(得分:0)
我不知道你是否已声明你的变量,如果没有那么请你这样做,你应该写下你的第二个for
循环,就像我在下面写的那样......
for(int j=0,int k=s-p; j<s-i, k>0; j++, k--)
因为多个初始化,条件和增量必须用逗号分隔。
答案 1 :(得分:0)
我希望仍然需要答案。代码的粗略概念是正确的,但是您有一些未定义的变量(如 i )以及有关使用列主矩阵的操作的一些错误:行
x[p] = b[p]/cm[s*s];
实际上必须是:
x[p] = b[p]/cm[s*s- 1];
只要我们在C谈话。无论如何,我只是发布有效的代码:
void backward_substitution (double *A, double *b, double *x, int rows)
{
//here: 'rows' is size of matrix eg: for 3x3 it is 3
//x[] where we put the result of backward substitution
//b[] it is the vector to be used.
//A[] is the square triangular matrix.
register int i,j;
// x(m,1) = b(m)/A(m,m); %% this is for the last row.
x[rows-1] = b[rows-1]/A[(rows-1)*rows + (rows-1)];
// for i = m-1:-1:1 % i starts at 2, end at 4, w/ steps of 1
// x(i,1) = ( b(i)- A(i,i+1:m)*x(i+1:m)) / A(i,i);
// end
for (i=(rows-2); i>=0; i--)
{
x[i] = b[i];
for (j=i+1; j<rows; j++)
{
x[i] -= A[(j)*rows + i]*x[j];
};
x[i] = x[i] / A[(i)*rows + i];
}; //for (i=1; i<rows; i++)
}; //void forward_substitution(double *A, double b*, int n)
为方便起见,这些注释包含MATLAB中的实际实现。享受。