Index in position 1 exceeds array bounds (must not exceed 2 )

Hi!
I'm trying to create a script that will manually find the LU factorization of a given matrix. This code seems to work for a 3x3 matrix, but once I increase the size to a 4x4 matrix, it seizes up and tells me that the index in the first position exceeds its bounds of 2. Here is the code:
clear all;
n = 4;
% Set up the 4x4 A matrix & b = column vector
disp(' n=4 ... Setting up 4x4 A matrix & b column vector ...')
n_rows = n ;
n_cols = n ;
A = [ 1 -2 -3 4 ;
-5 6 7 -8 ;
9 -10 11 -12 ;
-13 14 -15 16 ] ;
%
% Remember to transpose (') from row matrix to column matrix
b = [ 1 2 3 4 ]' ;
disp(' and initial L = U = A ...')
disp(' Warning: Up to you to reassign L and U ...')
L(:,1)=A(:,1)
U(1,:)=A(1,:)/L(1,1)
for k=2:size(A,2)
for j=2:size(A,2)
for i = j:size(A,2)
L(i,j) = A(i,j) - sum ( L(i,1:j-1)*U(1:j-1,j) )
end
U(k,j) = ( A(k,j) - sum( L(k,1:k-1)*U(1:k-1,j) ))/L(k,k)
end
end
It seizes up during the line "L(i,j) = A(i,j) - sum ( L(i,1:j-1)*U(1:j-1,j) )" and displays "Index in position 1 exceeds array bounds (must not exceed 2).
Error in set_Ab4 (line 24)
L(i,j) = A(i,j) - sum ( L(i,1:j-1)*U(1:j-1,j) )"
I've tried everything I can think up and find on here but nothing seems to make it want to finish. Any ideas?

댓글 수: 2

You are growing U as you go. The number of rows of U does not exceed k. But j can exceed k+1 and you have not created the full diagonal U(j-1,j) to be able to access it.
Oh darn! Thinking about this, I went ahead and created L and U to be 4x4 matrices filled with zeros at the beginning of the script, and that did the trick! Thanks!

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

질문:

2020년 9월 15일

댓글:

2020년 9월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by