Skip to content

Instantly share code, notes, and snippets.

@yuchung-chuang
Created February 22, 2019 06:42
Show Gist options
  • Save yuchung-chuang/2d5baf82fd6ad8df5ca9c8991e053c48 to your computer and use it in GitHub Desktop.
Save yuchung-chuang/2d5baf82fd6ad8df5ca9c8991e053c48 to your computer and use it in GitHub Desktop.
Inverse matrix
function B=M_det(A) %Handwrited n*n matrix determinant function
[n,n1]=size(A);
if n~=n1
fprintf('Error using det\nMatrix must be square.\n')
elseif n==1
B=A;
elseif n==2
B=det2(A);
else
B=det3(A);
end
end
function B=det2(A)
B=A(1,1)*A(2,2)-A(1,2)*A(2,1);
end
function B=det3(A)
C=A;
[~,n]=size(A);
B=0;
for k=1:n
C(1,:)=[];
C(:,k)=[]; %make submatrix
if size(C)==2 %tell if C is a smallest submatrix
if rem(k+1,2)==0 %tell if 1+k is even
B=B+A(1,k)*det2(C);
C=A;
else
B=B-A(1,k)*det2(C);
C=A;
end
else
B=B+det3(C); %recursive make submatrix and get det(C)
end
end
end
function B=M_inv(A) %Handwrited n*n matrix inverse function
if M_det(A)==0
fprintf('Warning: Matrix is close to singular or badly scaled. Results may be inaccurate.\n')
end
[n,~]=size(A);
B=zeros(n);
for i=1:n
z=A;
a=1;
while a<=n %set augmented matrix of x
if a==i
z(a,n+1)=1;
a=a+1;
else
z(a,n+1)=0;
a=a+1;
end
end
for j=1:n-1 % get up triangle matrix of x
for k=j+1:n
a=z(k,j)/z(j,j);
z(k,:)=z(k,:)-z(j,:)*a;
end
end
for j=n:-1:2 %get diagonal matrix of x
for k=j-1:-1:1
a=z(k,j)/z(j,j);
z(k,:)=z(k,:)-z(j,:)*a;
end
end
for j=1:n
B(j,i)=B(j,i)+z(j,n+1)/z(j,j);
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment