How to rearrange an out of order upper triangular matrix?

8 views (last 30 days)
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
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.
Truman Sacco
Truman Sacco on 29 Apr 2020
example input A: [ 0 1 2 4,
2 2 1 1,
0 0 0 3,
0 0 1 1]
b = [1;2;3;1] idk probably doesn't solve but you get the idea
output is rearranged A with rearranged b vec to correspond, and x (solution vec)

Sign in to comment.

Accepted Answer

Truman Sacco
Truman Sacco on 29 Apr 2020
Edited: Ameer Hamza on 29 Apr 2020
function [A,b,x] = ordersolve(A,b)
[n,m] = size(A);
rowct = 1;
A2 = zeros(n,n);
x = 0;
for i = 1:1:m
c = n - x - 1
for j = 1:1:c
A1 = A(j,i)
if(A1 ~= 0)
A2(rowct,:) = A(j,:);
A(j,:) = [];
b2(rowct,:) = b(j,:);
b(j,:) = [];
rowct = rowct + 1;
A2
x = x-1
break
end
end
end
A = A2;
b = b2;
% this is backward substitution
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
figured it out!

More Answers (0)

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!