Vectorization of For loops including If condition

1 次查看(过去 30 天)
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

回答(1 个)

Walter Roberson
Walter Roberson 2023-3-10
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 个评论
ilyes louahem m'sabah
I appreciate your answee. Would you please give an example on the logical indexing in this example?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by