Vectorization of For loops including If condition

조회 수: 1 (최근 30일)
ilyes louahem m'sabah
ilyes louahem m'sabah 2023년 3월 10일
댓글: ilyes louahem m'sabah 2023년 3월 11일
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
ilyes louahem m'sabah 2023년 3월 11일
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