solve larger than 3x3 matrix and error message
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Nicolas Schmit
2017-11-1
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!