Calling subfunctions from a loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Jan
am 1 Nov. 2015
Bearbeitet: Jan
am 1 Nov. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!