Reputation: 21
I don't find a solution to this problem
In my initialization I define an array "R" with certain number of values (the boolean flag with have the same length too). Later in my code I do an addition with a boolean flag.
Do you have an idea how to "update" this addition without editing it manually?
The part of the code i want to improve is
( (R(5)*B(i,5))+ (R(1)*B(i,1)) + (R(3)*B(i,3)) +(R(4)*B(i,4)) +(R(2)*B(i,2)) )
Thank you in advance for you answear
the code :
% i reflects the time
% bollean flag type double
B(1,:)=[0 0 0 0 0];
B(2,:)=[0 0 0 0 0];
B(3,:)=[0 0 0 0 1];
B(4,:)=[0 0 0 1 0];
B(5,:)=[0 0 0 1 1];
%info1
E(1)=0;
E(2)=0;
E(3)=10;
E(4)=20;
E(5)=40;
%info2
R = [1/30 1/30 1/30 1/30 1/30];
for i=1:5
for k=1:5
if E(i)>0
powerload_R2(i,k)= ( ( R(k))/( (R(5)*B(i,5))+ (R(1)*B(i,1)) + (R(3)*B(i,3)) +(R(4)*B(i,4)) +(R(2)*B(i,2)) ) ) *B(i,k)*E(i)+0; % fonctionnel
else
powerload_R2(i,k)= 0;
end
end
end
'end'
results
%results
powerload_R2(i,k)=
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
Upvotes: 0
Views: 65
Reputation: 5559
Your code could be greatly simplified. As @AnderBiguri has mentioned, this long line (R(5)*B(i,5))+ (R(1)*B(i,1)) + (R(3)*B(i,3)) +(R(4)*B(i,4)) +(R(2)*B(i,2))
is just the sum of the product of R
elements with the corresponding elements of the ith row of B
, or simply dot(R,B(i,:))
.
Also you can initialize powerload_R2 = zeros(5)
and alter only those rows corresponding to E > 0
. This way, you only have to iterate find(E > 0)
times over the rows of powerload_R2
and you don't need the inner k
loop. That said, loops are not as evil these days as they used to be on the early years of MATLAB, so use the most natural way to write your algorithm before thinking about vectorization for speed.
% 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 = find(E > 0)
powerload_R2(i,:) = R ./ dot(R,B(i,:)) .* B(i,:)*E(i); % fonctionnel
end
Upvotes: 1