How can I resolve this problem regarding nested functions?
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens

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 commentaires
Réponses (3)
Geoff Hayes
le 4 Avr 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 commentaires
David Hill
le 4 Avr 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 commentaires
Steven Lord
le 4 Avr 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 commentaires
Voir également
Catégories
En savoir plus sur Function Creation dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!