필터 지우기
필터 지우기

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