Calling subfunctions from a loop
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!