How to arrange correctly with a loop
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello,
I have created a matrix and need to get a result of a vector using by the Gauss Diesel method.
This gives me an error because of the large iterations. What did I do wrong here ..
Thanks for the helpers
x = zeros(1,4^2);
x_new=x; %x_new is the k+1 step
epsilon = 1e-3;
flag = 0;
counter = 0;
while flag == 0
counter = counter + 1;
if counter > 10000
error('Too many iterations');
end
end
f=4*ones(1,4^2);
m=diag(f);
j=0;
while j~=4^2
[m(j+1,j+2)]=-1;
[m(j+1,j+4)]=-1;
[m(j+2,j+1)]=-1;
[m(j+4,j+1)]=-1;
j=j+1 ;
end
A=m(1:4^2,1:4^2);
b=zeros(1,4^2);
b(1)=1;
b(4^2)=1;
for i = 1:4^2
x_new(i) = (b(i) - sum(A(i,1:i-1).*x_new(1:i-1)) - sum(A(i,i+1:4^2).*x((i+1):4^2)))/A(i,i);
end
if max(abs(x_new-x)./abs(x_new)) < epsilon
flag = 1;
end
VectorOut=x_new';
댓글 수: 0
답변 (1개)
Walter Roberson
2020년 12월 9일
The only thing you do in your while loop is increment the counter and test to see if it has become too large.
You need to extend your while loop to include more of the code.
j=0;
while j~=4^2
[m(j+1,j+2)]=-1;
[m(j+1,j+4)]=-1;
[m(j+2,j+1)]=-1;
[m(j+4,j+1)]=-1;
j=j+1 ;
end
That looks like you programmed your code in C originally and converted it to MATLAB.
for j = 1 : 16
m(j, j+1) = -1;
m(j, j+3) = -1;
m(j+1, j) = -1;
m(j+3, j) = -1;
end
or
j = 1 : 16;
m(j, j+1) = -1;
m(j, j+3) = -1;
m(j+1, j) = -1;
m(j+3, j) = -1;
댓글 수: 3
Walter Roberson
2020년 12월 9일
Either of the two sections I posted should work.
Your existing code for that section should work, but it is not well written.
The end you have just before
f=4*ones(1,4^2);
needs to be moved to the bottom of your code.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!