Calling subfunctions from a loop

1 visualización (últimos 30 días)
MG
MG el 1 de Nov. de 2015
Editada: Jan el 1 de Nov. de 2015
Hi, I am trying to get matlab to run certain loops based on conditions. In my primary function, my_factorial, I want to have the option of either calling a for loop to be executed, or a while loop. Both loops calculate the same thing- factorials- but I want to have the option of only calling one of them. So far I have the following and it isn't working. What is wrong with my primary function? Every time I specify an n in the command window, and an m, matlab runs through the entire thing which isn't what I want.
function f = my_factorial(n, m)
if m == 'for_loop'
f = fact1(n);
else m == 'while_loop';
f = fact2(n);
end
end
function f = fact1(n); my for loop end
function f = fact2(n); my while loop end

Respuesta aceptada

Jan
Jan el 1 de Nov. de 2015
Editada: Jan el 1 de Nov. de 2015
The == operator performs an elementwise comparison. Then m == 'for_loop' must fail, if m and the string do not have the same number of elements. The error message (which should be included in a question in the forum) should tell this clearly.
Better:
if strcmp(m, 'for_loop')
...
or:
switch m
case 'for_loop'
...
It is surprising to read, that Matlab "runs through the entire thing", because the original code should stop with an error. Anyway, the debugger is an excellent tool to find out, what's going on: http://www.mathworks.com/help/matlab/debugging-code.html
  1 comentario
MG
MG el 1 de Nov. de 2015
Thank you so much! I had tried the second case before, but I inputted "switch f" instead of "switch m". Thanks!!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by