How to turn a function with a for loop into a recursive function

조회 수: 7 (최근 30일)
Lee Cohen
Lee Cohen 2019년 4월 18일
답변: ag 2025년 2월 5일 18:06
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!

답변 (1개)

ag
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!

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by