variables not being saved?
댓글 수: 7
Hi @Olivia,
I have updated both functions. The updated provided code consists of two functions: lumine and lusolver.The lumine function performs the LU decomposition of a given coefficient matrix A and returns the lower matrix L and upper matrix U. It follows the following steps:Checks if the matrix A is square. If not, it throws an error and also if the matrix A is singular. If yes, it throws an error.Then, it initializes L as an identity matrix and U as A.Performs the LU decomposition using nested loops.Updates the rows of U and store the factors in L and sets the diagonal elements of L to 1.The lusolver function takes the lower matrix L, upper matrix U, and a vector B as inputs and solves the system of linear equations using LU decomposition. It follows the following steps:Initializes vectors y and x with zeros., performs forward substitution to solve Ly = B and backward substitution to solve Ux = y. Afterwards, returns the solution vector x.
Lumine Function
function [L,U] = lumine(A)
% lumine: LU decomposition
% input:
% A = coefficient matrix
% output:
% L = lower matrix
% U = upper matrix
[m,n] = size(A); % defines m and n
if m ~= n % checks if the matrix is square
error('Matrix A must be square');
end
if det(A) == 0 % checks if the matrix is singular
error('Matrix cannot be singular');
end
% Initialize L as an identity matrix and U as A
L = eye(n);
U = A;
for k = 1:n % starts at position 1, goes to the last column for i = k+1:n % starts at row after k, goes to second to last row
factor = U(i,k)/U(k,k); % defines factor
U(i,k:n) = U(i,k:n) - factor * U(k,k:n); % update row i of U
L(i,k) = factor; % store factor in L
end
end
% The diagonal of L should be set to 1 (identity property) for i = 1:n
L(i,i) = 1;
end
end
q = [2 1 -1; 4 0 2; 8 1 0];
[L,U] = lumine(q); % Now both L and U will be defined correctly.
disp('Matrix L:');
disp(L); % Display the lower matrix L
disp('Matrix U:');
disp(U); % Display the upper matrix U
Lusolver function
function solution = lusolver(L, U, B)
n = length(B);
y = zeros(n, 1);
x = zeros(n, 1);
% Forward Substitution (Ly = B)
for i = 1:n
y(i) = B(i) - L(i,1:i-1)*y(1:i-1);
end
% Backward Substitution (Ux = y)
for i = n:-1:1
x(i) = (y(i) - U(i,i+1:n)*x(i+1:n)) / U(i,i);
end
solution = x;
end
B = [-1;-2;-3];
solution = lusolver(L,U,B);
disp(solution);
Please see attached.
Hope, after this detailed explanation and provided two updated functions, your problem is resolved. Please let me know if you still have any further questions.
답변 (2개)
댓글 수: 0
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!