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 Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by