# Gauss Elimination - making my upper triangular matrix

20 views (last 30 days)
wei yang ng on 1 Oct 2022
Answered: Walter Roberson on 1 Oct 2022
Hi I was trying to figure out how to make the upper triangular matrix for a matrix of unspecified length (nxn), but my line 7 keeps getting an error and I can't seem to figure out why. Please help thank youu and my code is below!!
function[x]=Gauss(a,b)
B=[a b];
n=length(b);
for j= 1:n
B=sortrows(B(j:n),'descend');
for i=j+1:n
B(i,:)=B(i,:)-((B(i,j)*B(j,:))/B(j,j));
end
end
Errors:
Index in position 1 exceeds array bounds. Index must not exceed 1.
Error in Gauss (line 7)
B(i,:)=B(i,:)-(B(i,j)/B(j,j))*B(j,:);

Walter Roberson on 1 Oct 2022
length(b) of a 2D array is defined as
length = 0 if isempty(b)
length = max(size(b)) otherwise
You should avoid using length() for anything that might be a matrix, as you do not know whether the size returned refers to rows or columns.
B=[a b];
B is the augmented matrix. Typically it would have multiple rows; it will have multiple columns unless a and b are both empty or one of them is empty and the other has only a single column.
B=sortrows(B(j:n),'descend');
You are using a single index for B. If B is 2D or B is a column vector then the result would be a column vector; if B happens to be a row vector (because a and b both have exactly one row) then B(j:n) would be a row vector. Either way it seems unlikely that sortrows() is the desired operation on what is either a row or column vector.
Notice that B(j:n) would be a subset of B. So each time through your for j loop, B is going to be getting smaller -- faster than you would expect. The first time through, you would be taking B(1:n), which would be length n. The second time through you would be taking B(2:n) which would give you a vector of length n-1 and that replaces B. The third time through you would take B(3:n) -- but B refers to the B that has already had B(1) removed in the previous iteration, so B(3:n) would correspond to what was originally B(4:n). The next time through, j=4, B(4:n) but that is relative to the B created in the pervious iteration, so it would be B(8:n) relative to the original matrix...
I would suggest to you that the B(j:n), if it were correct at all, should be referring to the original B, not to the output of the sortrows() of the partial B.
Perhaps you want to sortrows() based upon columns j to n -- which is something that you can do with sortrows()

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!