Accepting multiple values for a function. I want my function to accept multiple values for beta
1 view (last 30 days)
Show older comments
function x = backsub(U,b)
%FORWARDSUB Solve a lower triangular linear system
%Input:
% U = Upper triangular matrix (n by n)
% b = right-hand side vector (n by 1)
% Output:
%Solution of Ux=b (n by 1 vector)
n = length(U);
x= zeros(n,1);
for i = 1:3
x(i) =( b(i) - U(i, 1:i-1)*x(1:i-1) ) / U(i,i);
end
end
alpha= 0.1; composition of specific matrix
beta= 1e1 (here lies the problem, i want the code to accept values of [10, 100, 1000 to 10^12])
U = eye(5)+ diag([-1 -1 -1 -1],1);
U(1,[4 5]) = [ alpha-beta, beta ];
x_exact = ones(5, 1);
b = [alpha;0;0;0;1];
x=backsub(U,b)
2 Comments
Bruno Luong
on 21 Sep 2023
Edited: Bruno Luong
on 21 Sep 2023
Is it recursive function (you call backsub in backsub)? How beta change between two recursion? When the recusion stops?
Walter Roberson
on 21 Sep 2023
I am pretty sure it is not intended to be recursive -- I think they posted the function and then the script to drive the function.
Answers (1)
Walter Roberson
on 21 Sep 2023
U(1,[4 5]) = [ alpha-beta, beta ];
when beta is a vector, then you have a problem: you need different 5 x 5 U matrices for each different value of beta. You are not operating on "the same U matrix but different beta values" each time: you are operating on different U matrices each time.
So you will need to either switch to 3D calculations, with U being 5 x 5 x length(beta), and appropriate adjustment for the backsub() function -- or else you will need to loop your code.
3 Comments
Walter Roberson
on 21 Sep 2023
Edited: Walter Roberson
on 22 Sep 2023
Looping...
But I didn't fix any bugs in your code.
format short g
alpha= 0.1; %composition of specific matrix
betas = 10.^(1:12);
baseU = eye(5)+ diag([-1 -1 -1 -1],1);
for K = 1 : length(betas)
U = baseU;
beta = betas(K)
U(1,[4 5]) = [ alpha-beta, beta ]
x_exact = ones(5, 1);
b = [alpha;0;0;0;1];
x=backsub(U,b)
end
function x = backsub(U,b)
%FORWARDSUB Solve a lower triangular linear system
%Input:
% U = Upper triangular matrix (n by n)
% b = right-hand side vector (n by 1)
% Output:
%Solution of Ux=b (n by 1 vector)
n = length(U);
x= zeros(n,1);
for i = 1:3
x(i) =( b(i) - U(i, 1:i-1)*x(1:i-1) ) / U(i,i);
end
end
Torsten
on 22 Sep 2023
for i = 1:n
x(i) =( b(i) - U(i, 1:i-1)*x(1:i-1) ) / U(i,i);
end
Why do you use a code for forward substitution if you need backward substitution ?
See Also
Categories
Find more on Particle & Nuclear Physics 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!