'Simplification code to avoid if else division problem
I would like to make an optimisation by avoiding to use theIf else
i used this element because when E = 0in the logic of my probelm B = [0 0 0 0 0].
By consequence I have an error Nan . I suppose it is because i have R/0 at i =1 and 2
% i reflects the time
% boolean flag type double
B = [0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1];
% info1
E = [0 0 10 20 40];
% info2
R(1:5) = 1/30;
powerload_R2 = zeros(5);
for i =1:5
if E(i)>0
powerload_R(i,:) = R ./ dot(R,B(i,:)) .* B(i,:)*E(i); % fonctionnel
else
powerload_R(i,:) = 0;
end
powerload_R2(i,:) = R ./ dot(R,B(i,:)) .* B(i,:)*E(i); %
end
%results
%what i get with :
powerload_R(i,:)=
0 0 0 0 0
0 0 0 0 0
0 0 0 0 10
0 0 0 20 0
0 0 0 20 20
powerload_R2(i,:)=
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
0 0 0 0 10
0 0 0 20 0
0 0 0 20 20
Solution 1:[1]
The NaNs appear from 0/0 division, so only add eps to the denominator to avoid this and get 0/eps = 0 instead.
% i reflects the time
% boolean flag type double
B = [0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1];
% info1
E = [0 0 10 20 40];
% info2
R(1:5) = 1/30;
powerload_R = zeros(5);
powerload_R2 = zeros(5);
for i = 1:5
if E(i) > 0
powerload_R(i,:) = R ./ dot(R,B(i,:)) .* B(i,:)*E(i); % fonctionnel
end
powerload_R2(i,:) = R ./ (dot(R,B(i,:))+eps) .* B(i,:)*E(i); %
end
Solution 2:[2]
Just for fun, the vectorized version of your formula is:
powerload_R = R ./ (B*R.') .* (B.*E.');
This results in:
powerload_R =
NaN NaN NaN NaN NaN
NaN NaN NaN NaN NaN
0 0 0 0 10
0 0 0 20 0
0 0 0 20 20
We can make a logical array to tell calculate only the rows where E is non-zero.
E_NZ = E ~= 0;
Then use E_NZ to index B and E:
powerload_R(E_NZ,:) = R ./ (B(E_NZ,:)*R.') .* (B(E_NZ,:).*E(E_NZ).');
So the complete script would look like this:
% i reflects the time
% boolean flag type double
B = [0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1];
% info1
E = [0 0 10 20 40];
% info2
R(1:5) = 1/30;
powerload_R = zeros(5);
E_NZ = E ~= 0;
powerload_R(E_NZ,:) = R ./ (B(E_NZ,:)*R.') .* (B(E_NZ,:).*E(E_NZ).');
The result is the same matrix without the NaN values and no (explicit) looping:
powerload_R =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 10
0 0 0 20 0
0 0 0 20 20
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AboAmmar |
| Solution 2 |
