Help with function putting a matrix into upper triangluar form.
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Geoff Hayes
2014-11-29
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!