MATLAB: If statement four variables

if statementMATLAB

Hi all, Thanks for your time in advance.
I have vectors which contain the kWh output of a wind turbine and demand data for a house beside that turbine, i want to create an if statement which will
  • If battery is fully charged && windpower>demand then Charge battery until is full
  • If battery is fully charged && wind<demand then Battchg=wind-demand
  • If battery is empty && wind>demand then Battchg=wind-demand
  • If battery is empty && wind<demand then import=demand-wind
I've been trying to implement this without any success for the last week. I'm relatively new to Matlab so apologies for the stupidity of this. What I've done so far is this
range=2000; %specify amount of data steps
D=importdata('data1.mat'); %import demand data
demand=D(1:range)'; % create demand vector
time=0:1:(range-1); % simple time vector
W=xlsread('wind_data'); % read wind data from excel
wind=W(1:range)'; %create wind vector
rho=1.2754; %assumed at 10degrees
R=2; %wind turbine radius
wind_p=(1/2*(pi*R^2)*(wind.^3))'; %simple windo power no efficiency etc.
subplot(2,1,1);
plot(time,demand,time,(wind_p/1000)); %wind power from kw to kwh
ax=gca; %add axis 16/11/2016
ax.YLabel.String = 'demand/wind power in kw';
ax.YLabel.FontSize = 12;
ax.XLabel.String = 'time (s)';
ax.XLabel.FontSize = 12;
cap=10;
chg=cumsum(wind_p/1000); %cumulative battery charge assuming 100% efficiency
chg(chg>cap)=cap; %battery can only hold value of cap
chg_per=(chg/cap)*100; %percentage charge
subplot(2,1,2);
plot(time,chg_per); % plotting battery charge
ax=gca;
ax.YLabel.String = 'battery charge percentage';
ax.YLabel.FontSize = 12;
ax.XLabel.String = 'time (s)';
ax.XLabel.FontSize = 12;
import=(0:range-1)'; %creating vector for if statement

export=(0:range-1)'; %creating vector for if statement
diff=wind_p>demand;
if chg_per==100 & diff==1
export=wind_p-demand;
if chg_per==100 & wind<demand
chg=wind-demand;
elseif chg_per~=100 & diff==0
import=wind_p-demand;
end
end

Best Answer

Ilona - diff is a built-in MATLAB function, so I would avoid using it as a name for a variable. I don't understand the first if statement: If battery is fully charged && windpower>demand then Charge battery until is full. If the battery is fully charged, why would you charge the battery until full?
Regardless, your if statements would look something like this
if abs(chg_per-100) < eps
if wind_p > demand
% do something

else
% do something else

end
elseif abs(chg_per) < eps
if wind_p > demand
% do something
else
% do something else
end
end
The above assumes that chg_per is the battery charge. Note that since this variable is a double, we cannot compare it to 100 (this sort of comparison is only valid for integers) and so we use a check to see if it is very close to 100 where eps is a small number. Likewise, if chg_per is less than eps, we assume that the battery is empty.
Related Question