How can I resolve this problem regarding nested functions?

조회 수: 15 (최근 30일)
Cyrus Adrian Tenorio
Cyrus Adrian Tenorio 2020년 4월 4일
답변: Steven Lord 2020년 4월 4일
function [root1, root2]= getreal(a,b,c);
getinput
function getinput
if a==0
disp('Error')
end
end
root1 = ((0-b) + sqrt(D))/2*a
root2 = ((0-b) - sqrt(D))/2*a
function calcdisc = D
disc = (b*b)-(4*a*c);
calcdisc = disc;
end
end
When I enter >>getreal(0,1,1), the script still manages to calculate for root1 and root 2.
function [root1, root2]= getreal(a,b,c);
getinput
function getinput
if a==0
disp('Error')
else
root1 = ((0-b) + sqrt(D))/2*a
root2 = ((0-b) - sqrt(D))/2*a
function calcdisc = D
disc = (b*b)-(4*a*c);
calcdisc = disc;
end
end
end
end
However, when I tried this solution, it displayed this error message
'Error: File: getreal.m Line: 10 Column: 12
Function definition is misplaced or improperly nested.'

답변 (3개)

Geoff Hayes
Geoff Hayes 2020년 4월 4일
Cyrus - from Requirements for Nested Functions, You cannot define a nested function inside any of the MATLAB® program control statements, such as if/elseif/else, switch/case, for, while, or try/catch. You have nested the function within the else block.

David Hill
David Hill 2020년 4월 4일
I assume you can use a nested anonymous function. Sounds like your getinput function needs to get all of the coefficients and check to make sure a~=0.
function [root1, root2]= getreal()
calcdisc=@(a)a(2)^2-4*a(1)*a(3);
function a=getinput()
a(1)=0;
while ~a(1)
a=input('Input quadratic coefficients in the form of an array, [a,b,c] (a~=0): ');
end
end
a=getinput();
root1=(-a(2)+sqrt(calcdisc(a))/(2*a(1)));
root2=(-a(2)-sqrt(calcdisc(a))/(2*a(1)));
end

Steven Lord
Steven Lord 2020년 4월 4일
Your first attempt is pretty close. Just a couple comments:
function [root1, root2]= getreal(a,b,c);
getinput
function getinput
if a==0
disp('Error')
disp doesn't stop execution of the function. You probably want your getinput function to stop execution if a is equal to 0. For that you should call the error function.
end
end
root1 = ((0-b) + sqrt(D))/2*a
root2 = ((0-b) - sqrt(D))/2*a
function calcdisc = D
This defines a function named D that returns a variable calcdisc. You probably want to reverse those, to define a function named calcdisc that returns a variable D.
function D = calcdisc
This will require changes to the body of the calcdisc function and to how you call it.
disc = (b*b)-(4*a*c);
calcdisc = disc;
end
end

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by