How to rearrange an out of order upper triangular matrix?
8 views (last 30 days)
Show older comments
PREREQ ------ A is a nxn matrix with random numbers, b is the corresponding answer vector,
here is my code:
function [A,b,x] = ordersolve(A,b) % I'm relatively new to matlab, so I wanted to put my thoughts on what I think my
% code is doing over here. If my logic doesn't match up to my code; which it
[n,m] = size(A); % most likely doesn't considering this post... please tell me! I want to learn!
rowct = 1; % initialize row count to 1,
A2 = A; % initialize a matrix of the same size, doesn't matter what it has in it because I'm replacing
% rows anyway, but it could have been made with zeros(n,m).
for i = 1:1:m % for each column,
for j = 1:1:n % for each row -- I want it to go through column by column :: for each row number in col m, check.
A1 = A(j,i) % create new number to hold the content of A(j,i).
if(A1 ~= 0) % if A1 isnt = to 0,
A2(rowct,:) = A(j,:); % A2 in the current row, starting at 1, is replaced with A row @ where number is not 0.
A(j,:) = []; % A then has its row erased so next time through the loop, that row won't be there anymore.
b2(rowct,:) = b(j,:); % ^ same logic
b(j,:) = [];
rowct = rowct + 1; % increase row count by 1; only whenever we find a diagonalnum.
end
end
end
A = A2; % replace variables that will be returned with the recalculated A2 and b2 matrices.
b = b2;
% this is backward substitution % <<---------- This whole part below was given already; I assume it runs correctly exactly as presented.
x = zeros(n,1);
for i = n:-1:1
x(i) = b(i);
for j = i+1:n
x(i) = x(i) - A(i,j)*x(j);
end
x(i) = x(i)/A(i,i);
end
end
2 Comments
Ameer Hamza
on 29 Apr 2020
Can you show a numeric example of your problem? Take an input matrix and describe the required output. It is easier to understand the problem by reading the description as compared to reading the code.
Accepted Answer
More Answers (0)
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!