solve larger than 3x3 matrix and error message

2 vues (au cours des 30 derniers jours)
amateurintraining
amateurintraining le 1 Nov 2017
I have a function:
function [A_new, b_new] = forward_elimination(A, b)
%FORWARD_ELIMINATION - Performs forward elimination to put A into unit
% upper triangular form.
% A - original matrix of Ax = b
% b - original vector of Ax = b
% A_new - unit upper triangular A formed using Gaussian Elimination
% b_new - the vector b associated with the transformed A
% Default output
A_new = A;
b_new = b;
[n,n]=size(A);
Ab=[A b];
Ab(1,:)=Ab(1,:)/Ab(1,1);
Ab(2,:)=Ab(2,:)/Ab(2,2);
Ab(3,:)=Ab(3,:)/Ab(3,3);
Ab(2,:)=Ab(1,:)*Ab(2,1)-Ab(2,:);
Ab(2,:)=Ab(2,:)/Ab(2,2);
Ab(3,:)=Ab(1,:)*Ab(3,1)-Ab(3,:);
Ab(3,:)=Ab(3,:)/Ab(3,2);
Ab(3,:)=Ab(2,:)*Ab(3,2)-Ab(3,:);
Ab(3,:)=Ab(3,:)/Ab(3,3);
A_new=Ab(:,1:end-1);
b_new=Ab(:,end);
if Ab(1,1)==0 || Ab(2,2)==0 || Ab(3,3)==0 || Ab(3,2)==0
error(zeros(n))
end
end
This produces the desired answer for a 3x3 matrix but how do I expand this for larger matrices. Also, how to i write the code such that if the system is unsolvable or is divided by 0, the algorithm responds an error message and returns a matrix of all zeros? I have attempted above.

Réponses (1)

Nicolas Schmit
Nicolas Schmit le 1 Nov 2017
how do I expand this for larger matrices.
use for loops
how to i write the code such that if the system is unsolvable or is divided by 0, the algorithm responds an error message and returns a matrix of all zeros?
You can first calculate the determinant of the matrix, and issue an error message if it is null.
  1 commentaire
amateurintraining
amateurintraining le 1 Nov 2017
I have attempted to fix the code:
function [A_new,b_new]=forward_elimination(A,b)
A_new=A;
b_new=b;
[n,n]=size(A)
if Ab(1,1)==0 || Ab(2,2)==0 || Ab(3,3)==0 || Ab(3,2)==0 || determinant_e7(A)==0
zeros(n)
error('function cannot compute')
end
for row=1:n-1
for i=row+1:n
factor=A(i,row)/A(row,row);
for j=row:n
A(i,j)=A(i,j)-factr*A(row,j);
end
b(i)=b(i)-factor*b(row);
end
A_new=A;
b_new=b;
end
end
But the code does not produce the UNIT matrices (with 1's in the diagonals and 0's under), and the error statement is incorrect. How should I go from here?

Connectez-vous pour commenter.

Catégories

En savoir plus sur Sparse Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by