How can I resolve this problem regarding nested functions?

16 次查看(过去 30 天)
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 中查找有关 MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by