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

2 visualizaciones (últimos 30 días)
FuManchuToo
FuManchuToo el 15 de Sept. de 2020
Comentada: FuManchuToo el 18 de Sept. de 2020
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 comentarios
Walter Roberson
Walter Roberson el 15 de Sept. de 2020
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.
FuManchuToo
FuManchuToo el 18 de Sept. de 2020
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!

Iniciar sesión para comentar.

Respuestas (1)

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam el 16 de Sept. de 2020
try this
for i = j:size(A,1)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by