nested function calculation problem

Hello everyone,
I'm trying to write a code that consists of an if and a nested function. I try, each nested function works seperately but It doesn't work when you put it together. The general structure is as follows. It enters the nested function and calculates correctly, but does not print the answer. Where is the problem?
Thanks
function abc(a1,b1,c1)
x;
y;
z;
function x
if statement
statement
else statement
statement
end
end
function y
if statement
else statement
end
end
function z
if statement
else statement
end
end
result=x+y+z
end

 Respuesta aceptada

Walter Roberson
Walter Roberson el 29 de Nov. de 2021

0 votos

Your functions do not return values. You cannot add them.

4 comentarios

Cem Eren Aslan
Cem Eren Aslan el 30 de Nov. de 2021
how can i return values? i try several times, it enter the nested function and it calculate corresponding values but when function end, values disappear.
With any function, the best approach is most often to just return values. For example,
function result = abc(a1,b1,c1)
x_val = x();
y_val = y();
z_val = z();
function xv = x()
if statement
statement
else statement
statement
end
xv = something;
end
function yv = y()
if statement
else statement
end
yv = something;
end
function zv = z()
if statement
else statement
end
zv = something;
end
result = x_val + y_val + z_val;
end
But that does not require nested functions (unless the nested functions access shared variables.) There is another opportunity with nested functions:
function result = abc(a1,b1,c1)
x_val = []; y_val = []; z_val = []; %must initialize, shared variables!
x;
y;
z;
function x
if statement
statement
else statement
statement
end
x_val = something; %no return value, modify shared variable
end
function y
if statement
else statement
end
y_val = something; %no return value, modify shared variable
end
function z
if statement
else statement
end
z_val = something; %no return value, modify shared variable
end
result = x_val + y_val + z_val; %but you need to return this
end
Walter Roberson
Walter Roberson el 30 de Nov. de 2021
Shared variables are slower than passing parameters in and returning outputs.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 29 de Nov. de 2021

Comentada:

el 30 de Nov. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by