Borrar filtros
Borrar filtros

How can I define a function within a loop?

13 visualizaciones (últimos 30 días)
Tanvir Kaisar
Tanvir Kaisar el 21 de Mzo. de 2017
Comentada: Adam el 21 de Mzo. de 2017
Say I want to repeat this user defined function within a loop with , how can I do it? Each time I do it like below I get this message - "Function definition is misplaced or improperly nested."
r=1;
while(1)
function y= myFunc (x)
y= -(500000*r*x(1));
r=r+1;
end
if (r>10)
break;
end
end
  3 comentarios
Tanvir Kaisar
Tanvir Kaisar el 21 de Mzo. de 2017
I am sorry where did you show? and I have not asked this question before! :O
Adam
Adam el 21 de Mzo. de 2017
You seem to be misunderstanding the fundamental difference between defining a function and calling it. You define it once and can call it as many times as you like. I'm sure this is covered in the documentation on functions though to be honest I've never needed to look since I know what a function is and how it works.

Iniciar sesión para comentar.

Respuesta aceptada

Star Strider
Star Strider el 21 de Mzo. de 2017
There is no need to define your function inside the loop.
Do something like this instead:
r=1;
myFunc = @(x,r) -(500000*r*x(1)); % Anonymous Function
while(1)
% DEFINE ‘x’ SOMEPLACE
y = myFunc(x,r)
r=r+1;
if (r>10)
break;
end
end
See the section on ‘Anonymous Functions’ in the documentation on Function Basics.

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by