Vectorization of For loops including If condition

1 view (last 30 days)
In this code I converted i and j from for loops to vectors. However, when i used the IF condition for Enet(i,k); where i is a vector and k is a loop i got soc(i,k) equals to 0 all the time while it must be values between 0.4 and 1.
It seems like it's not conmputing the IF condition.
t
ic
%------Input data----------
Npvmin=1; %Min nbr of PV
Npvmax=100;
Cbmin=31.2;
Cbmax=124.2;
soc=[ ];
socmx=1; %max soc
socmn=0.4; %min soc
% ------Calculating Enet, and soc for each hour------
i=Npvmin:Npvmax;
j=Cbmin:31.2:Cbmax;
jj=1:length(j);
socmax=j; socmin=(1-0.6)*socmax; chargelimit=0.3*j;
w=0;
Enet=zeros(length(i),length(Em1kWh)); % Em1kWh is a 8760x1 input data array
soc=zeros(length(i),length(Em1kWh));
for k=1:8760
Enet(i,k)= i'*Em1kWh(k)- Load(k); % here Enet(i,k) is calculated without any problem
if Enet(i,k)>0 %------Pout > Pload % this conditionis satisfied
if k==1
soc(i,k)=socmx; % here soc must be equal to socmx =1, but i get always 0.
elseif k>1
if w==0
soc(i,k)=socmx; % i get always 0
elseif w==1
if soc(i,k-1)>=socmx
soc(i,k)=socmx;
elseif soc(i,k-1)<socmx
%-------charging mode----------%
if Enet(i,k)<=chargelimit
soc(i,k)=soc(i,k-1)+(1/j)*Enet(i,k);
if soc(i,k)>socmx
soc(i,k)=socmx;
else soc(i,k)=socmn;
end
elseif Enet(i,k)>chargelimit
soc(i,k)=soc(i,j,k-1)+(1/j)*chargelimit;
if soc(i,j,k)>socmx
soc(i,k)=socmx;
else soc(i,k)=Enet(i,k)-chargelimit;
end
end
end
end
end
end
end
toc

Answers (1)

Walter Roberson
Walter Roberson on 10 Mar 2023
When you use if or while the condition is considered to be true only if all of the values being tested are non-zero (testing nan would generate error.)
if x < 3
is equivalent to
if all(x(:) < 3)
if and while will never automatically apply branches of the code only to entries considered true: if any of the entries are not considered true (non-zero) then the condition fails entirely.
You need to use logical indexing instead.
  1 Comment
ilyes louahem m'sabah
ilyes louahem m'sabah on 11 Mar 2023
I appreciate your answee. Would you please give an example on the logical indexing in this example?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!