Accepting multiple values for a function. I want my function to accept multiple values for beta
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Bruno Luong
2023-9-21
编辑:Bruno Luong
2023-9-21
Is it recursive function (you call backsub in backsub)? How beta change between two recursion? When the recusion stops?
Walter Roberson
2023-9-21
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.
回答(1 个)
Walter Roberson
2023-9-21
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 个评论
Walter Roberson
2023-9-21
编辑:Walter Roberson
2023-9-22
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
2023-9-22
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 ?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Particle & Nuclear Physics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!