Converting For loops into recursive functions

2 ビュー (過去 30 日間)
Max
Max 2015 年 11 月 5 日
回答済み: Walter Roberson 2015 年 11 月 5 日
What are the general ideas of converting for loops and nested for loops I have written into recursive functions that dont need loops to run. Is there anywhere I can learn more about recursive functions. Thanks

回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 11 月 5 日
Example:
function total = total_it(X)
total = 0;
for K = 1 : length(X)
total = total + X.^K;
end
end
can be changed to
function total = total_it(X)
total = total_it_worker(X,1);
end
function total = total_it_worker(X,K)
if isempty(X)
total = 0;
else
total = X(1).^K + total_it_worker(X(2:end),K+1);
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by