Help with function putting a matrix into upper triangluar form.
3 views (last 30 days)
Show older comments
I have this function but it just is not doing what I want it to. When the function reaches to the end of the second for, it goes through that same for loop over again. How can I fix this? The Largest, swap and matCon are my own functions, they fins the row with the largest value, swap two rows and create a liner combination of the rows.
%%Converts a matrix to upper triangular form
function [upperMat]=upperTriangle(M)
rows=size(M,1);
cols=size(M,2);
for curRow=1:rows-1;
maxRow=Largest(M,curRow,curRow);
if maxRow>curRow;
M=swap(M,maxRow,curRow);
end
for workRow=curRow+1:rows
alpha=-M(workRow,curRow)/M(curRow,curRow);
M=matCon(M,curRow,workRow,alpha);
end
upperMat=M;
end
end
0 Comments
Accepted Answer
Geoff Hayes
on 29 Nov 2014
Marc - you probably need to post the code for your three functions as one of them may be causing a problem. If I take your code and use the following substations for your three
function [maxRowIdx] = Largest(M,startRowIdx,colIdx)
[~,maxRowIdx] = max(M(startRowIdx:end,colIdx));
end
function [M] = swap(M,row1Idx,row2Idx)
temp = M(row1Idx,:);
M(row1Idx,:) = M(row2Idx,:);
M(row2Idx,:) = temp;
end
function [M] = matCon(M,row1Idx,row2Idx,alpha)
M(row2Idx,:) = alpha*M(row1Idx,:) + M(row2Idx,:);
end
then the algorithm works. For example
upperTriangle(magic(5))
ans =
23 5 7 14 16
0 20.304 -4.1739 -2.3478 3.1739
0 0 12.837 18.158 18.415
0 0 0 -9.3786 -31.28
0 0 0 0 90.173
5 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!