How to convert a For loop function into an If function
이전 댓글 표시
I have a question. As i am using a MATLAB function block. I cannot use recursive functions like for loop and while loop. Therefore, I need to replace my code using If function. I have a code which has an for loop within a while loop function as shown below. How to i convert it to If function or is there other ways to not use recursive function?
while abs((max(Pnew)-min(Pnew))/max(Pnew))>0.05
for i = 1:4
f = 0.3 + (0.5-0.3)*B;
vnew(i) = vold(i)+(DPold(i) - DPbest)*f;
if DPold(i) > DPbest(i)
DPnew(i) = DPold(i) - abs(vnew(i));
else
DPnew(i) = DPold(i) + abs(vnew(i));
end
if rand(0,1)>rold(i)
DPnew(i) = DPold(i) + mean(Aold)*e;
end
D = DPnew(i);
Pnew(i) = P;
if Pnew(i) < Pold(i)
DPnew(i) = DPold(i);
Pnew(i) = Pold(i);
end
Anew(i) = 0.5*Aold(i);
rnew(i) = rold(i)*(1-exp(-0.5));
end
end
DPbest = max(DPnew);
D = DPbest;
댓글 수: 1
for, while, if are not functions. They are statements. A function in matlab will always start with the statement function, or starts with an @(.
for and while have nothing to do with recursive functions. Usually you would replace a recursion by a for or while loop. The code you show does not use recursion.
The purpose of for and while is repeating a task. The purpose of if is choosing alternative tasks. Completely different purpose. You can't swap one for the other.
It's really unclear what your problem is and what you want to achieve.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 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!