Say I want to repeat this user defined function within a loop with , how can I do it? Each time I do it like below I get this message - "Function definition is misplaced or improperly nested."
r=1;
while(1)
function y= myFunc (x)
y= -(500000*r*x(1));
r=r+1;
end
if (r>10)
break;
end
end

댓글 수: 3

John D'Errico
John D'Errico 2017년 3월 21일
You just asked this same question, answered. What was wrong with the last answer, where I showed how to create a similar function in a loop?
Tanvir Kaisar
Tanvir Kaisar 2017년 3월 21일
I am sorry where did you show? and I have not asked this question before! :O
Adam
Adam 2017년 3월 21일
You seem to be misunderstanding the fundamental difference between defining a function and calling it. You define it once and can call it as many times as you like. I'm sure this is covered in the documentation on functions though to be honest I've never needed to look since I know what a function is and how it works.

댓글을 달려면 로그인하십시오.

 채택된 답변

Star Strider
Star Strider 2017년 3월 21일

0 개 추천

There is no need to define your function inside the loop.
Do something like this instead:
r=1;
myFunc = @(x,r) -(500000*r*x(1)); % Anonymous Function
while(1)
% DEFINE ‘x’ SOMEPLACE
y = myFunc(x,r)
r=r+1;
if (r>10)
break;
end
end
See the section on ‘Anonymous Functions’ in the documentation on Function Basics.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 3월 21일

댓글:

2017년 3월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by