How to arrange correctly with a loop

1 次查看(过去 30 天)
Emilia
Emilia 2020-12-9
评论: Emilia 2020-12-9
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';

回答(1 个)

Walter Roberson
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
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.
Emilia
Emilia 2020-12-9
I tried to make this code not work, returns an error.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by