How can I nest a function in a function?
조회 수: 1 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Fangjun Jiang
2022년 10월 13일
MyAD=AD(3)
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
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
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)
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
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 Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!