MATLAB: How to convert a For loop function into an If function

if functionmatlab function block

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;

Best Answer

First, I think when you are saying "recursive" you mean "looping". While and For loops aren't inherently recursive. A recursive function calls itself. In any case, assuming you want to rewrite your code without loops you are "vectorizing" your MATLAB code. One of the great powers of MATLAB compared to other programming languages is its ability to operate on entire vectors or matrices without needing loops. If you want to get the benefits of using MATLAB it is important to be able to take advantage of this power. I would suggest you start by reading https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
Just a few ways you could use vectorization in your code include replacing
vnew(i) = vold(i)+(DPold(i) - DPbest)*f
with
vnew = vold + (DPold-DPbest)*f
You can also use "logical indexing" which selects just those elements of a vector, or matrix that meet a certain logical criteria, to replace for example
if Pnew(i) < Pold(i)
DPnew(i) = DPold(i);
with
idl = Pnew < Pold
DPnew(idl) = DPold(idl)
Finally, just a suggestion for future posts, it is good to use the Code button in the MATLAB Answers toolbar to include code. That way it comes out nicely formatted, and is easy to copy, so that respondents can try out your code.