Calling subfunctions from a loop

1 次查看(过去 30 天)
MG
MG 2015-11-1
编辑: Jan 2015-11-1
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

采纳的回答

Jan
Jan 2015-11-1
编辑:Jan 2015-11-1
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 个评论
MG
MG 2015-11-1
Thank you so much! I had tried the second case before, but I inputted "switch f" instead of "switch m". Thanks!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by