Skip to content

Instantly share code, notes, and snippets.

@mrfarhadir
Created January 15, 2019 14:45
Show Gist options
  • Save mrfarhadir/54a705120b56b892720ef10d4cefd906 to your computer and use it in GitHub Desktop.
Save mrfarhadir/54a705120b56b892720ef10d4cefd906 to your computer and use it in GitHub Desktop.
% LU Matrix decomposition algorithm
% Author: Farhad Mehryari
% Web: blog.mrfarhad.ir
function [ L, U ] = LU(A)
% A شرط بررسی مربعی بودن ماتریس
sz = size(A);
if sz(1)~=sz(2)
fprintf('A is not square !\n');
clear x;
return;
end
n = sz(1);
L = eye(n);
P = eye(n);
U = A;
for i=1:sz(1)
% کاهش سطری
if U(i,i)==0
maximum = max(abs(U(i:end,1)));
for k=1:n
if maximum == abs(U(k,i))
temp = U(1,:);
U(1,:) = U(k,:);
U(k,:) = temp;
temp = P(:,1);
P(1,:) = P(k,:);
P(k,:) = temp;
end
end
end
if U(i,i)~=1
temp = eye(n);
temp(i,i)=U(i,i);
L = L * temp;
U(i,:) = U(i,:)/U(i,i); % بررسی اینکه محور ها الزاما یک باشند
end
if i~=sz(1)
for j=i+1:length(U)
temp = eye(n);
temp(j,i) = U(j,i);
L = L * temp;
U(j,:) = U(j,:)-U(j,i)*U(i,:);
end
end
end
end
% Author: Farhad Mehryari
% Web: blog.mrfarhad.ir
A=[4 5;6 8]
[l u]=LU(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment