I would like to make an optimisation by avoiding to use theIf else
i used this element because when E = 0
in 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
CodePudding user response:
The NaN
s 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
CodePudding user response:
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).');
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