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!