Answers
Ok, your algorithm is a bit off the mark. You were thinking along the right paths, however. For these kinds of problems, the best way to learn is to do the steps by hand and then thinking about how you will implement them via code.
I have provided both the text and the screenshot for your better understanding. The screenshot also has some comments for your help. Please note that this is a script file which is to be saved as backsub.m in your MATLAB root directory.
The script backsub.m gives the value of the variable matrix as output.
The input must be a square upper triangular non-singular matrix with none of the diagonal elements as 0.
backsub.m
function x = backsub(U,b)
n = length(b); %calculating size of solution vector
x = ones(size(b)); %initializing solution vector
for i=n:-1:1
x(i) = b(i)/U(i,i); %solving the last row of the matrix
b(1:i-1) = b(1:i-1) - U(1:i-1,i)*x(i); %updating the constant values so that the previous row can now be treated as the last row of the matrix
end
fprintf("result of backward substitution\n");
disp(x);
end
OUTPUT
I have attached screenshots for 3 random test cases, one of them in the question and the other 2 from random sources.
Example matrix in question
3x3 matrix
4x4 matrix
*A humble request* - If you have any doubt, please use the comment section to communicate. This will clarify your doubt, and also help me to get better at answering your next questions. At the same time, If my answer helped you, please consider leaving an upvote. I hope you understand my viewpoint. Thank you :)