How can I nest a function in a function?

1 回表示 (過去 30 日間)
Barbaros Teoman Kosoglu
Barbaros Teoman Kosoglu 2022 年 10 月 13 日
コメント済み: John D'Errico 2022 年 10 月 13 日
function AD = AD(n)
A = zeros(n);
for i=1:n
for j=1:n
A(i,j) = 1/(i+j-1);
end
end
Ainv = A\eye(n);
Eye = eye(n);
AD = Eye-Ainv*A;
end
function A = hilbert(n)
A = zeros(n);
for i=1:n
for j=1:n
A(i,j) = 1/(i+j-1);
end
end
end
I want to nest hilbert function in AD function, since hilbert is actually in AD. But I am getting "Unrecognized function or variable 'A'" error. What can I do here?

採用された回答

Fangjun Jiang
Fangjun Jiang 2022 年 10 月 13 日
MyAD=AD(3)
MyAD = 3×3
1.0e-13 * 0 0 0.0089 -0.0711 0 0 0.1421 0.0711 0.0711
function AD = AD(n)
A = hilbert(n);
Ainv = A\eye(n);
Eye = eye(n);
AD = Eye-Ainv*A;
end
function A = hilbert(n)
A = zeros(n);
for i=1:n
for j=1:n
A(i,j) = 1/(i+j-1);
end
end
end
  2 件のコメント
Barbaros Teoman Kosoglu
Barbaros Teoman Kosoglu 2022 年 10 月 13 日
Thank you.
Fangjun Jiang
Fangjun Jiang 2022 年 10 月 13 日
To be clear, hilbert(n) here is a 'local function'. There is no need to make it a 'nested function' based on its content.
See documents for their differences.
I think 'local function' is more suitable in this case.

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

その他の回答 (1 件)

John D'Errico
John D'Errico 2022 年 10 月 13 日
編集済み: John D'Errico 2022 年 10 月 13 日
See that I wrote hilbert differently. Feel free to use doubly nested loops there. But why?
As well, NEVER name a function the same thing as a variable in that function!!!!!!!!! NEVER. NEVER. Having said that three times, it must be true. You named the function AD, then returned a variable named AD. A BAD idea.
ComputeAd(5)
ans = 5×5
1.0e-11 * 0.0171 0 -0.0071 -0.0099 -0.0099 0.0909 0.0455 0.1592 0.1137 0.1137 -0.3638 -0.3638 -0.1819 -0.1819 -0.3638 0.7276 0.3638 0.3638 0.3638 0.5457 -0.1819 -0.0909 -0.0909 -0.1819 -0.2728
It works.
function AD = ComputeAd(n)
A = hilbert(n);
Ainv = A\eye(n);
Eye = eye(n);
AD = Eye-Ainv*A;
function A = hilbert(n)
[i,j] = meshgrid(1:n);
A = 1./(i+j-1);
end
end
  3 件のコメント
VBBV
VBBV 2022 年 10 月 13 日
編集済み: VBBV 2022 年 10 月 13 日
Check with
ComputeAd(5)
Matlab is case senstive. You might have used
ComputeAD(5)
This is different function and not present in code you copied
John D'Errico
John D'Errico 2022 年 10 月 13 日
Yes. You tried to call ComputeAD, but I named the function ComputeAd. Sorry about my choice of names.
Case sensitivity triumphs there. MATLAB told you it could not find that function, the clue you needed.

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

カテゴリ

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

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by