How to compose a function n-times and want value for a particular value of n?

19 ビュー (過去 30 日間)
Sayantan Panja
Sayantan Panja 2020 年 9 月 30 日
コメント済み: Ameer Hamza 2020 年 10 月 1 日
Suppose f(x)=x^2+1. Composition of two f, I mean f(f(x)), Similarly composition of 3 f is f(f(f(x))). n-th composition of f is denoted by f^n(x).
What is the general command to evaluate f^10(2) ?

採用された回答

Bruno Luong
Bruno Luong 2020 年 9 月 30 日
f = @(x) x.^2-x;
n = 10;
x = 1/pi;
y = x;
for k=1:n
y = f(y)
end
% y is f^10(x)

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 9 月 30 日
編集済み: Ameer Hamza 2020 年 9 月 30 日
Use recursion
f = @(x) x.^2 + 1;
n = 2;
fn = nRecursion(f, n);
function f = nRecursion(f, n)
if n == 1
f = @(x) f(f(x));
return
else
f = nRecursion(f, n-1);
end
end
f, and fn are function handles.
Example
>> f(f(5))
ans =
677
>> fn(5)
ans =
677
>> f(f(10))
ans =
10202
>> fn(10)
ans =
10202
  2 件のコメント
Sayantan Panja
Sayantan Panja 2020 年 10 月 1 日
It shows :Undefined function or variable 'nRecursion'."
Ameer Hamza
Ameer Hamza 2020 年 10 月 1 日
No, Run it inside a script. It will not work directly on the command line.
You can also do it like this. Create a file named nRecursion.m in MATLAB path and paste the following code in it
function f = nRecursion(f, n)
if n == 1
f = @(x) f(f(x));
return
else
f = nRecursion(f, n-1);
end
end
and then run
f = @(x) x.^2 + 1;
n = 2;
fn = nRecursion(f, n);
in command window.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by