Can someone please help me stop "Index exceeds array bounds." in iteration? Any help is highly appreciated.

조회 수: 1 (최근 30일)
clc
A = [4 -1 -3;-2 6 1;-1 1 7];
b=[3;9;-6];
D=diag(diag(A))
[L,U]=lu(A)
Mj = D\(U+L)
Mj(:,3)=[];
Mj(:,2)=[];
Vj =D\b
x1=zeros;
x=zeros;
for n = 2:8
x = Mj*('the previous x value')+ Vj;
end
x

채택된 답변

Clayton Gotberg
Clayton Gotberg 2021년 4월 18일
편집: Clayton Gotberg 2021년 4월 18일
You're asking for elements in x1 that don't exist. If we look only at the last loop n == 8 and you are asking for x1(7), but x1 is defined just before as being a 3x1 matrix of zeros.
I also want to point out that x1 is always zero in the code you posted here, so x will always equal Vj. Additionally, x is being overwritten on every loop instead of the value in each loop being saved.
  댓글 수: 2
Yunusah Abdulai
Yunusah Abdulai 2021년 4월 18일
편집: Yunusah Abdulai 2021년 4월 18일
Thank you. I had noticed. I still have a problem in the iteration. please help me
clc
A = [4 -1 -3;-2 6 1;-1 1 7];
b=[3;9;-6];
D=diag(diag(A))
[L,U]=lu(A)
Mj = D\(U+L)
Mj(:,3)=[];
Mj(:,2)=[];
Vj =D\b
x=zeros;
for n = 2:8
x = Mj*('the previous x value')+ Vj;
end
x
Clayton Gotberg
Clayton Gotberg 2021년 4월 18일
The previous value of x is just x. When programming, you are allowed to change the value of a variable using a reference to itself:
x = 5; % Define an initial value for x
x = x+5: % Define a new value for x: x = x (which we defined as 5) + 5
% Now, x == 10

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

the cyclist
the cyclist 2021년 4월 18일
In your for loop, when n==5, your code tries to execute
x1(n-1)
which is
x1(4)
But your vector x1 is length 3, so there is no 4th element to access. That's why you get that error.
  댓글 수: 1
Yunusah Abdulai
Yunusah Abdulai 2021년 4월 18일
편집: Yunusah Abdulai 2021년 4월 18일
I edited the the code and i have this but i still have a problem with the iteration
clc
A = [4 -1 -3;-2 6 1;-1 1 7];
b=[3;9;-6];
D=diag(diag(A))
[L,U]=lu(A)
Mj = D\(U+L)
Mj(:,3)=[];
Mj(:,2)=[];
Vj =D\b
x1=zeros;
x=zeros;
for n = 2:8
x = Mj*('the previous x value')+ Vj;
end
x

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by