Equations which depend on each other with unknown initial value
이전 댓글 표시
Hi all,
I want to solve equations which depend on each other such as,
5*x_1 = 3*x_2 + 4
4*x_2 = 2*x_1 + 4*x_3 + 4
4*x_3 = 2*x_2 + 4*x_4 + 4
3*x_4 = 6*x_3 +4
I usually put the coefficients of the variables into matrix
A = [5 -3 0 0; -2 4 -4 0; 0 -2 4 4; 0 0 -6 3]
C = [4;4;4;4]
B = inv(A) * C
and get the result, since the number of variables can change and go up to 100, I wrote a 'for loop'
n=4;
for i = 2:n-1
x(1) = (3*x(2) + 4)/5
x(i) = (2 * x(i-1) + 4 *x(i+1) +4)/4
x(n) = (3 * x(i-1) + 4) / 3
end
but the results are not same, i think in the for loop matlab assumes x(2) as zero and continues, anyway if someone can solve this problem I appreciate.
Thanks.
답변 (1개)
Walter Roberson
2019년 11월 5일
n=4;
x = sym('x', [1 n]);
x(1) = (3*x(2) + 4)/5;
for i = 2:n-1
x(i) = (2 * x(i-1) + 4 *x(i+1) +4)/4;
end
x(n) = (3 * x(i-1) + 4) / 3;
댓글 수: 4
Erkin Karatas
2019년 11월 5일
Walter Roberson
2019년 11월 6일
n=4;
x = sym('x', [1 n]);
eq(1) = (3*x(2) + 4)/5;
for i = 2:n-1
eq(i) = (2 * x(i-1) + 4 * x(i+1) +4)/4;
end
eq(n) = (3 * x(n-2) + 4) / 3;
xval = vpasolve(eq);
Now xval.x1, xval.x2, xval.x3, and so on.
Erkin Karatas
2019년 11월 6일
Walter Roberson
2019년 11월 6일
You should go through the equations and make sure that they are correct.
Note: when you construct equations in symbolic form, it is not necessary to do the division by 4 and whatever. You can code things like 5*x(1) == 4*x(2) + 4 inside the eq vector.
카테고리
도움말 센터 및 File Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!