How to turn a function with a for loop into a recursive function
조회 수: 7 (최근 30일)
이전 댓글 표시
Hello, I have a task to write a recursive function, that solves a system with an upper-triangular coefficient matrix. I mean, to solve the system: Ax=b, when A is an upper-triangular coefficient matrix
I wrote a function using for loop, howover I don't know how to turn it into a recursive function. Here's my code:
function x=uppermatsolve(M,b);
x=zeros(size(b));
[n,m]=size(M);
x(n,:)=b(n,:)/M(n,n);
for k=n-1:-1:1
x(k,:)=(b(k,:)-M(k,k+1:n)*x(k+1:n,:))/M(k,k);
end
Any help is greatly appreciated!
댓글 수: 0
답변 (1개)
ag
2025년 2월 5일 18:06
Hi Lee,
To convert your iterative function into a recursive one, you need to redefine the problem in terms of smaller subproblems. For an upper-triangular matrix, the recursive approach involves solving the last equation first and then recursively solving the reduced system. Here's how you can achieve this:
function x = uppermatsolve_recursive(M, b)
% Get the size of the matrix
[n, ~] = size(M);
% Initialize the solution vector
x = zeros(size(b));
% Call the recursive function
x = recursiveSolve(M, b, x, n);
end
function x = recursiveSolve(M, b, x, k)
% Base case: solve the last equation
if k == 1
x(k) = b(k) / M(k, k);
else
% Recursive case: solve for the current variable
x(k) = (b(k) - M(k, k+1:end) * x(k+1:end)) / M(k, k);
% Recursively solve for the next variable
x = recursiveSolve(M, b, x, k-1);
end
end
Hope this helps!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!