Function code
function [Pgrid, Pcharge, Pdischarge, SOC_new] = fcn(SOC, Ebatt, dt, Cost, Ppv, Pload)
% SIMULINK-COMPLIANT ENERGY MANAGEMENT SYSTEM
%% 1. INITIALIZE ALL OUTPUTS FIRST
Pgrid = 0;
Pcharge = 0;
Pdischarge = 0;
SOC_new = SOC;
%% 2. CONVERT ALL ARRAYS TO SCALARS (FIX FOR LOGICAL OPERATORS)
Pload = Pload(1); % Take first element
Ppv = Ppv(1); % Take first element
Cost = Cost(1); % Take first element (THIS FIXES THE ERROR)
%% 3. Handle missing inputs
if nargin < 6
if nargin < 1, SOC = 0.5; end
if nargin < 2, Ebatt = 100; end
if nargin < 3, dt = 1; end
if nargin < 4, Cost = 0.25; end
if nargin < 5, Ppv = 30; end
if nargin < 6, Pload = 50; end
end
%% 4. Parameters
SOC_min = 0.2;
SOC_max = 0.9;
Cost_threshold = 0.3;
Pmax_batt = max(1, Ebatt / 2);
%% 5. Bound inputs
SOC = max(SOC_min, min(SOC, SOC_max));
Pload = max(0, min(Pload, 1000));
Ppv = max(0, min(Ppv, 1000));
Cost = max(0, Cost);
%% 6. Net load calculation
netLoad = Pload - Ppv;
%% 7. SIMULINK-COMPLIANT LOGIC
if netLoad < -0.01
% Case 1: Surplus PV → Charge battery
if SOC < SOC_max
Pcharge = min(-netLoad, Pmax_batt);
SOC_new = SOC + (Pcharge * dt) / max(1, Ebatt);
end
elseif netLoad > 0.01
% Case 2: Load deficit → Discharge or grid
% NOW Cost IS SCALAR - NO LOGICAL OPERATOR ERROR
if Cost > Cost_threshold && SOC > SOC_min
Pdischarge = min(netLoad, Pmax_batt);
SOC_new = SOC - (Pdischarge * dt) / max(1, Ebatt);
netLoad = netLoad - Pdischarge;
end
if netLoad > 0
Pgrid = netLoad;
else
Pgrid = 0;
end
else
% Case 3: Balanced
Pgrid = 0;
end
%% 8. Final bounds
SOC_new = max(SOC_min, min(SOC_new, SOC_max));
End
Commnd window
✅ Working directory: C:\MATLAB_Projects\Microgrid_Simulation
✅ Data Size Verification:
Time: 24x1
Pload: 24x1
Ppv: 24x1
Cost: 24x1
✅ All variables saved to workspace
✅ Testing MATLAB Function...
Function test FAILED: Undefined function 'fcn' for input arguments of type 'double'.
✅ MICROGRID SIMULATION READY!
Next Steps:
1. Open your Simulink model: microgrid_WithESSOpt
2. Set From Workspace blocks:
- Load: Use 'LoadStruct' or 'Load_Matrix'
- PV: Use 'PVStruct' or 'PV_Matrix'
- Cost: Use 'CostStruct' or 'Cost_Matrix'
3. Set Constant blocks:
- SOC: Use 'SOC_Constant' (0.5)
- Ebatt: Use 'Ebatt_Constant' (100)
- dt: Use 'dt_Constant' (1)
4. Run simulation (Ctrl+T)
Simulation will run for 24 hours (0 to 23)
Workspace saved as: Microgrid_Perfect_Data.mat
Data visualization completed
>> %% FIX: Create Proper Workspace Data for From Workspace Block
Time = (0:23)';
PV_Data = [0 0 0 0 0 5 15 30 45 60 70 75 80 75 70 60 45 30 15 5 0 0 0 0]';
% Create matrix format for From Workspace block
PV_Matrix = [Time, PV_Data];
% Save to workspace
assignin('base', 'PV_Matrix', PV_Matrix);
fprintf('✅ PV_Matrix created successfully!\n');
fprintf('Size: %dx%d\n', size(PV_Matrix));
✅ PV_Matrix created successfully!
Size: 24x2