How to turn a function with a for loop into a recursive function
6 views (last 30 days)
Show older comments
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 Comments
Answers (1)
ag
on 5 Feb 2025
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 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!