MATLAB: Hi, I try to convert this matlab code to VB.NET or C# codes. Help me please..

MATLABmatrix manipulation

The function is :
function X=space_bound(X,up,low)
[N,dim]=size(X);
for i=1:N
% %%Agents that go out of the search space, are reinitialized randomly .
Tp=X(i,:)>up;
Tm=X(i,:)<low;
X(i,:)=(X(i,:).*(~(Tp+Tm)))+((rand(1,dim).*(up-low)+low).*(Tp+Tm));
% %%Agents that go out of the search space, are returned to the boundaries.
% Tp=X(i,:)>up;Tm=X(i,:)<low;X(i,:)=(X(i,:).*(~(Tp+Tm)))+up.*Tp+low.*Tm;
end
——————— The question is: what does it mean the lines code:
Tp=X(i,:)>up;
Tm=X(i,:)<low;
X(i,:)=(X(i,:).*(~(Tp+Tm)))+((rand(1,dim).*(up-low)+low).*(Tp+Tm));
Thank's

Best Answer

Well, really, the best way for you to find out what it is doing is to go and ask whoever wrote that horror (and at the same time, complain that the logic is not documented.
The exact equivalent of these three lines would be (assuming that low is not greater than up)
outofrange = X(i, :) > up | X(i, :) < low;
X(i, outofrange) = rand(1, sum(outofrange)) * (up-low) + low;
which simply set the values of the row that are out of range to a random number between low and up.
Note that the loop wasn't even needed, this
function X = space_bound(X, up, low)
outofrange = X > up | X < low
X(outofrange) = rand(1, sum(outofrange)) * (up-low) + low;
end
would achieve the same.
Here is the truth table for the original code, clearly written by somebody who has never heard of logical operators
X>up X<low |
Tp Tm | Tp+Tm ~(Tp+Tm) | X.*(~(Tp+Tm) | rand.*(Tp+Tm) | whole expression
0 0 | 0 1 | X | 0 | X+0 = X
0 1 | 1 0 | 0 | rand | 0+rand = rand
1 0 | 1 0 | 0 | rand | 0+rand = rand
1 1 | 2 0 | 0 | 2*rand | 2*rand !
So as you can see the effect of the whole expression is to copy X(i,j) into X(i,j) when it is in range and replace it with a random value when it is not. Note that from the comments, it's clear that the author assumed that the last case (X>up and X<low) would not occur. However, since there's actually no check, if the user mistakenly swap up and low (and why aren't they called high and low?) then the original code results in invalid values. The replacement using logical operators does not suffer from that issue.
Related Question