How can I resolve this problem regarding nested functions?
13 views (last 30 days)
Show older comments
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.'
0 Comments
Answers (3)
Geoff Hayes
on 4 Apr 2020
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.
0 Comments
David Hill
on 4 Apr 2020
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
0 Comments
Steven Lord
on 4 Apr 2020
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
0 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!