Memuat
Memuat
Watch every step above performed live, with English narration.
0 plays
Class book
Page 1 / 34
Cover: MATLAB Class for Optimizing PV Plant and Inverter for Hydrogen LCOH
Click a page or use ◀ ▶ to turn · swipe on mobile · to enlarge
Want to go deeper?
Join one of our courses or ask us directly on WhatsApp.
Picked from the software, topic, and level of “MATLAB Class: MATLAB Tutorial: Optimizing PV Plant and Inverter Capacity for the Lowest Hydrogen Cost (LCOH)”.
Other ways we can help with MATLAB R2025b.
Learn with a mentor
Scheduled Simulation & Engineering courses with live guidance and a certificate.

Course/Training Ansys ~ Heat Transfer and Heat Flux Analysis
★ 5.0 (10)

Course/Training MATLAB — MATLAB App Design: The Ultimate Guide to MATLAB Apps
★ 5.0 (10)

Course/Training Ansys — Airflow Simulation of a Car Radiator with ANSYS
★ 5.0 (9)
Have it built for you
No time to learn MATLAB R2025b? Our team can do the project for you.

Matlab Development Service — Complete Neural Signal Processing and Analysis Zero to Hero
★ 5.0 (59)

Ansys Maxwell Development Service
★ 5.0 (50)

Petrel Development Service
★ 5.0 (14)
Get notified about new MATLAB R2025b classes
At most one email a week. Unfollow anytime with one click.
The full narration of this video. The current sentence is highlighted while the video plays; click any sentence to jump there.
Here is the result we will get, a hydrogen cost map against the capacity of the PV plant and inverter, and the optimal configuration of 67.76 kWp with an inverter of 46 kW. Let's start from a new project. Hello, welcome. In this video, we will determine the optimal capacity of the PV plant and inverter for the hydrogen production plan of PLTU Banten 2 Labuan. With the target of the lowest hydrogen production cost, or LCOH. All work is done from scratch in MATLAB. From a new project, we download solar data, write all code line by line, run the particle swarm optimization, until validation and sensitivity analysis. The background comes from a thesis proposal. The hydrogen plan uses a constant load of 40 kW for 24 hours. The PV plant is installed without batteries on the northern side of the warehouse shelter roof. The power deficit is met by the PLN I3 tariff grid, and the latest renewable energy attribute is purchased through REC certificates. Between 10 AM to 2 PM, the load must be fully met by the PV plant, while surplus has no export value, so the inverter cuts its peak power. The question is, how many kW peak PV and how many kW inverter, so that the hydrogen cost is the lowest? We take the parameters from the reference thesis and proposal. Load of 40 kW, hydrogen production of 3,149 kg per year, so the specific energy consumption is 111.26 kW hours per kg. Solar data from PIVGIS LONG modules 560 Watt-Pick CAPEX $1013 per kW peak, tariff I3, 114.74 kW hours, REC price Rp46,375 per MW hour, discount 9.28%, project lifespan 25 years. The star mark is my assumption as a researcher, which we will test later. The workflow has 8 stages Each stage is one MATLAB script, and all of them use the same evaluation function, so the results of the scenario, PSO, and grid search can be compared equally. All these files will be typed from scratch. The main point is the hourly model. PV power is calculated from capacity multiplied by the PIVGIS profile, cut by the inverter, used for the load, and the rest is taken from the grid. Grid energy determines the amount of REC. All costs are discounted to obtain LCOH in rupiah per kilogram, then converted to dollars.
We start from scratch. This is a newly opened MATLAB. The working folder is still the home folder, and our project does not exist yet.
In the address bar, we navigate to the PLTS H2 tutorial folder, which is still empty. We create four project folders using the MACDIR command via cell phone.
01 data for data, 02 MATLAB for programs, 03 results, and 04 images. Notice the files panel, the four folders appear directly. The CD20 MATLAB command moves the working folder to the program folder. Our solar data is downloaded from PIVGIS.
The API address is arranged in the URL variable, latitude minus 6,39, longitude 105,82, data base year 5 years 2023, system 1 kWp crystalline silicon, system loss 10%, tilt 11 degrees, azimuth 180 meaning facing north, and output format CSV. The web survey function downloads data from that address and saves it to the 01 data folder. We wait for a few seconds. With redliness, we read the file. Then the disk displays lines 12-17, column titles, which are time and power P in Watts, followed by data rows for each hour. The time is still in UTC. The data is ready. Now we start writing the program, from an empty file. First, a helper function for graph style. In the command window, we type edit gaya underscore gambar. MATLAB asks if a new file is created, we click yes.
We start from the helper function for graph style. The first line declares the function gaya gambar without input, with one output named C, which is the color palette. This comment line explains the purpose of the function, setting the graph display to be consistent and returning the color palette. The set command on growth, which is the root object for all MATLAB graphs, changes the default values. First, the axis font becomes area. The default axis font size becomes 11. The text font type, such as title and labels, also becomes area. The box around the axis is turned off for a cleaner appearance. The axis line thickness is 0.8, and the default plot line thickness is 1.8. Grid lines on the X and Y axes are turned on, with a thin transparency of 0.15 to avoid disturbing the data. The next seven lines define the color palette as fill for structure C. Blue, orange, green, red, purple, gray, and yellow. Each color is a vector of three numbers for red, green, blue, with values between 0 and 1. The word N closes the function. Save with Ctrl + S, and the file is complete.
Second helper function, create underscore figure. The method is the same, edit, then yes.
Second helper function, create figure, accepts window name as well as width and height in pixels, and returns the figure handle. The comment explains, creating the graphics window and placing it in the center of the screen. The figure command creates a new graphics window with a name, position, and size width by height, as well as a white background color. Movegui with the center option moves the window to the center of the screen, so the graphics appear neatly in front of the editor. And N closes the function. Save with Ctrl + S, and the file is complete.
Third helper function, save underscore image.
Third helper function, save image, accepts figure, structure parameter, and file name. Its task is to save the figure to the images folder as a png 220 dpi. If the images folder does not exist, it is created with macdir. The function exists with the dir argument to test the folder's existence, and the tilde sign means not. Export grab Higgs saves the figure to a png file in the images folder. The file name is composed of the name plus .png, with a resolution of 220 dpi. Closing function.
Save with Ctrl+S, and the file is complete. Now the parameter file. All our research numbers are collected here.
Now the most important file for data, the M point parameter file. All research numbers are collected here for easy modification. The function has no input and returns one structure named par. Three lines of comments explain its contents, the technical and economic parameters of the research, according to Table 3.1 and 3.2 of the proposal, for the optimization of rooftop on-grid PV and inverter with minimum LCOH in the hydrogen plan of PLTU Banten 2 Labuan. Two percent signs create the section title. First section, project folder. The file name with the full part option gives the location of this file, then the file parts take the folder name, which is 02 matlab. Saved in the file location. The parent folder, which is the project folder, we save as part dot dir dot root. The data folder is organized with full files from the project folder and 01 data. With full files, the program runs on any computer as long as the folder structure is the same. In the same way, we prepare the results folder 03 results and the images folder 04 images. Second section, location and climate data. PLTU coordinates, latitude minus 6.391633 degrees and longitude 105.828228 degrees. This value is used when retrieving data from PIVGIS. The CSV file location of PIVGIS that we have already downloaded to the data folder. Time zone difference, WIB is UTC plus 7 hours. Part three, load and hydrogen. Hydrogen load from PLN PLOAT, 40 kW constant for 24 hours. NH is the number of hours in a year, 8760. MH2 is the annual hydrogen production, 3149.3952 kg, from the reference thesis. SEC, specific energy consumption, calculated from annual energy, which is load times hours, divided by hydrogen production. The result is 111.26 kW hours per kilogram. Part four, PV plant and inverter. MOD, power of 1 module LONG. 0.56 kW pit. AMOT, area of 1 module, length 2.278 meters times width 1.134 meters. A atap, area of the northern side roof of the shelter, 2131.5 square meters. F atap, area utilization factor 0.8. This is my assumption for the service path and roof edge, and will be tested later. Maximum number of modules, used area divided by module area, rounded down with floor. DC to AC ratio limit, minimum 1.0 and maximum 1.5. Grid capacity step, 1 module for PV plant and 1 kW for inverter. Used by PSO and grid set. Part five, effective hour constraints. Effective hours are hours starting at 10, 11, 12, and 13, meaning from 10 to 14 Indonesia Western Time. Clear days are selected from 25% days with the highest energy. Part six, economic parameters, all in rupiah. Average exchange rate for 2024, 15.850 rupiah per dollar to convert CAPEX. Reporting exchange rate 18.000 rupiah per dollar to state LCOH final. CAPEX System, 1.013 dollars per kilowatt peak multiplied by exchange rate. Already includes inverter. Inverter cost is $80 per kilowatt, this is my assumption, then converted to rupiah per kilowatt. DC to AC ratio is 1.2. Module and support costs are calculated by subtracting the inverter cost per kilowatt peak from CAPEX System, according to equation 3.13. O&M and PLTS costs, $6.19 per kilowatt peak per year, in rupiah. PLN electricity tariff for group I3, 1,114.74 rupiah per kilowatt hour. DPP for self-consumption from PLTU, 548 rupiah per kilowatt hour. REC price, 46,375 rupiah per megawatt hour. One REC is equivalent to 1 megawatt hour. Discount rate is 9.28 percent, which is WAP PLN. Project lifetime is 25 years. Inverter is replaced in year 15. Part 7, PSO parameters. Number of particles is 40 and maximum iterations is 120. Inertia weight decreases from 0.9 at the beginning to 0.4 at the end. Cognitive coefficient and social coefficient, each two. Search stops if 30 iterations do not improve, and stability test uses 30 independent runs. Last part, PSO search space bounds. Lower bound of PLTS is the load rounded up to the nearest module multiple, and upper bound is from the maximum number of modules. Lower bound of inverter is equal to the load, and upper bound is the maximum PLTS capacity divided by the minimum ratio. And N closes the parameter function.
Save with Ctrl S, and the file is complete.
We test in the Command Window by typing par equals parameter. Matlab displays all parameters as a structure. Then partik PSO displays PSO settings, 40 particles, 120 iterations, inertia weight from 0.9 to 0.4, and cognitive and social coefficients each two. Next, the 'olah_pifgis' function, to process the pifgis data we just downloaded.
The 'olah_pifgis' function takes par and returns a PV structure containing the solar power profile. Comment: Reading the pifgis 8760-hour data, converting it to WIB, and creating a clear day profile. Step 1, reading the data row by row. Readliness reads the entire CSV content as a string array, one element per row. Regex searches for lines starting with 8 digits of date, dot 2, 4 digits of hour, then a comma. Only the pifgis data lines that match. The result is a line marker. Split breaks the data lines into columns by comma. The second column is the solar power 1 kWp in Watts, converted into a number with STR 2 double. Assert ensures the data count is exactly 8,760 hours. If not, the program stops with a message. Step 2, convert UTC to WIB and normalize. Kirkshift shifts by 7 hours so that UTC time becomes WIB, then divided by 1000 so the unit is kW per kWp. Step 3, arrange the daily matrix. Reshape arranges 8,760 data into a 24 hours x 365 days matrix. Daily energy per kWp is the sum of each column. Step 4, select representative clear days, 25% highest energy. Number of clear days, 25% of 365 rounded, which is 91 days. Sort with the opsi desgen option sorts daily energy from the largest. The variable urut stores the day numbers. Take the top 91 days, then reorder the numbers. Median of each hour on the clear days becomes the clear day profile, 24 values factor. Step 5, arrange the output. Number of days in each month. Cumsum provides the last day of each month, and the first day is counted from there. Start filling the PV structure, series S, daily matrix S, daily energy, number of clear days, and clear day profile. The lowest profile value is at the effective hour. Index is added by 1 because MATLAB starts counting from 1. Annual specific productivity is the total of the series. Monthly energy is calculated with arraifun, summing daily energy from the first day to the last day of the month. Lower bound of PV capacity, load divided by the lowest profile value at the effective hour. End of function.
Save with Ctrl S, and the file is done. Then the first step script, P01 datap VIFGIS, which calls the function above and draws the results.
Now the first step script, P01. The title line starts with two percent signs so it becomes a section title in the editor. Process VIFGIS data from UTC to WIB and select representative clear days. Clear removes variables, CLC cleans the command window, and close all closes all figures, so the script always starts from a clean condition. Call the plot style to set the appearance and save the color palette in C, then parameters to load all parameters into the structure par. Process VIFGIS reads CSV, shifts time, and generates the PV structure. The result is saved to the PV.mat file in the results folder, so the next script does not need to process it again. The first FRINF command prints the annual specific productivity with one decimal. The percent point 1F code is where the number goes, and the slash N moves to a new line. The second line prints the number of clear days. Two percent signs are printed as one percent sign, and percent D is for integer from numel, which is the number of elements. Third, the lowest median profile value at the effective hour, with three decimals. Fourth, the lower bound of PV capacity, which is load divided by the lowest value above. First part of the plot, daily profile and monthly energy. Create figure makes the graphics window size 1150 x 450. Select layout to split the window into one row and two column panels with close spacing. Time axis, hours 0-23 added with half, so the points are centered within each hour. Nextile moves to the first plot, and hold on, you can draw several lines on the same axis. The patch draws a transparent yellow rectangle marking the effective hours 10-14. The dashed gray line, average over all 365 days, from min in the second dimension. The orange line with a circle, median profile for sunny days. Label the X and Y axes, and set the X-axis limits from 0 to 24. Legend with three annotations, placed at the north, i.e., the top part. First map title. The slash key produces the degree symbol. Go to the second map. The toolbar is drawing a monthly energy bar chart, in blue. The X-axis labels from 1-12 are replaced with month names, Jan to Des. Label Y-axis and title. Sprint inserts the annual total energy into the title. Save the image to save this graph as Vick 01. Second image section, selecting a sunny day. A new window of size 700 x 450, and hold on. First histogram. Daily energy distribution over all 365 days, 24 groups, in gray. Second histogram. Only sunny days, in orange. Label the X and Y axes. Legend. 365 days, and 25% of the highest days. Graph title. Save as Vick 02. Script P01 is complete.
Save with Ctrl S, and the file is done.
We click the Run button in the Editor tab. Annual specific productivity 1486.6 kWh per kWh, 91 sunny days, and the lowest profile value at effective hours 0.593. This means that the PV plant needs at least 67.46 kWh to meet the 40 kWh load.
Two graph windows appear in the middle of the screen, and both are automatically saved as PNGs in the 04 images folder.
This is the PV power profile on a sunny day. The yellow area represents effective hours from 10 to 14.
On the right, the highest monthly energy is from August to October.
And here is the selection of representative sunny days, 25% of days with the highest daily energy, colored orange. Now the most important part, the system calculation function, hourly simulation, and LCOH calculation.
This is the core function, system calculation. Inputs are PAR structure, PV data, PV plant capacity PPV, inverter capacity PINF, and the electricity source option which can be left blank. Output is a structure R containing all the results. Three lines of comments explain, the hourly simulation follows equations 3.1 to 3.10 and LCOH follows equations 3.11 to 3.18, the meaning of PPV and PINF, and the electricity source option, which is PLN grid plus RHC or self-consumption. Nargin is the number of arguments provided. If less than 5, the default electricity source is grid. Load L is taken from parameter 40 kW. First part, hourly operation model. All the following calculations are in factors of 8,760 hours at once. Equation 3.1, available PV power is capacity multiplied by TIFGIS profile. Equation 3.2, inverter AC output is the minimum between PV power and inverter capacity. This is where clipping, or peak clipping, occurs. Equation 3.3, the power used by the load is the smallest value between the AC output and the load. Equation 3.4, the power deficit is taken from the PLN grid. Equation 3.5, the power clipped by the inverter. Equation 3.6, the AC power exceeding the load, called curtailment, has no value because it is not exported. Annual energy from the grid and the used load, by summing the power per hour. Clipped energy, curtailment energy, and total PV energy. Part two, REC, hydrogen, and solar fraction. If the electricity source is the grid, it is compared with STRC MP. The required REC is the grid energy divided by one thousand, rounded up with CEL, because one REC equals one megawatt-hour. This is equation 3.8. The tariff used is the PLN grid tariff. Conversely, in self-consumption, there is no REC. And the tariff uses the self-consumption BPP. End of branch. Equation 3.10, solar fraction is the used energy divided by the annual load energy. Part three, cost in rupiah. Yearly factor from 1 to 25. Transpose makes it into a column. Discount factor each year, 1 divided by 1 plus discount rate, raised to the power of the year. Equation 3.12, KPEX is the module cost multiplied by the PLTS capacity plus the inverter cost multiplied by the inverter capacity. Equation 3.14, annual O and N cost of the PLTS. Equation 3.15, annual grid electricity cost, tariff multiplied by grid energy. Equation 3.16, annual REC cost. Equation 3.17, annual inverter replacement cost. A PPV value greater than 0 is only applicable if there is a PV plant. The current value of O&M cost, grid cost, and REC cost, which is annual cost multiplied by the discount factor. The current value of inverter replacement cost, using the discount factor for the replacement year. The current value of hydrogen production, referred to as LCOH. Equation 3.11, LCOH in rupiah per kilogram is total current value of cost divided by current value of hydrogen production. Part four, constraints. AC output on the clear day profile during effective hours is limited by the inverter. Violation G1, how much the minimum output is less than the load, expressed relatively. Zero means the effective hour constraint is satisfied. If there is a PV plant, the DC to AC ratio is the capacity of the PV plant divided by the capacity of the inverter. Violation G2 is the largest of zero, the deficiency against the lower bound, and the excess against the upper bound of the ratio. If there is no PV plant, the ratio is undefined and G2 is zero. End of branch. Part five, arranging the output. These four lines describe the input, ratio, and total annual energy, as well as the hourly power series to the structure R. Capex in rupiah. Annual cost, O&M plus grid plus REC, without inverter replacement. Details of grid cost, REC, and inverter replacement cost. LCOH in rupiah per kilogram. Equation 3.18 is converted to dollars using the reporting exchange rate. Comment, LCOH components. Multiplier to convert the current value of cost to dollars per kilogram. Vector of five LCOH components, Capex, O&M, grid electricity, REC, and inverter replacement. Constraint violation is saved. Viable solution if both violations are zero. Closing the function.
Save with Ctrl S, and the file is done. Before proceeding, let's test this function directly in the Command Window.
Load parameters and PV data, then calculate the previous research configuration, 75.6 kW peak with a 75.6 kW inverter. LCOH of 7.45 dollars per kilogram, energy from the grid of 245,000 kW·h per year, and the effective hour constraint is satisfied, shown by the value 1 on VASIBLE. Step 2 script for the reference scenario and model verification.
Step 2 script, calculating reference scenarios 1 to 3 and verifying the model. Clear variables, command window, and graphs. Load parameters, then load PV data from the PV.mat file resulting from step 1. Scenario 1, self-consumption of the coal power plant with BPP, without PV and REC. Call the system calculation with capacity 0 and PS source. Scenario 2, PLN grid class I3 plus REC, without PV. Scenario 3, the previous research design, 75.6 kW peak and 75.6 kW inverter. Printing the comparison table title. The 34S percentage code prints left-aligned text of 34 characters. LCOH line in dollars per kilogram for the 3 scenarios. Energy taken from the grid in kW·h per year. REC requirement in units. Solar fraction, which is the portion of load energy met directly by PV. Constraint status for effective hours for scenario 3, violation B1 and whether VASIBLE. Verification section, power balance every hour must be 0. The largest difference between the used power plus grid power and load throughout the entire hour. Printing that difference in scientific notation. Asar stops the program if the difference is not 0 or there is negative grid power. Save the three scenarios to the scenario123.mat file.
Save with Ctrl S, and the file is complete.
Let's run it. Scenario 1, self-consumption electricity with BPP, 3,39 dollars per kilogram. Scenario 2, PLN grid with REC without PLTS, 7,18. Scenario 3, previous research design, 7,46. Power balance difference is 0, so the model is consistent. For optimization, we need a fitness function.
Fitness function LCOH calculates the fitness value for PSO. Inputs are position X, which is a pair of PLTS and inverter capacities already mapped to the grid, as well as parameters, data, and penalty coefficients. Call calculate system with capacities from X. Equation 3,26, fitness is LCOH plus penalty multiplied by the number of constraint violations G1 and G2. End of function.
Save with Ctrl S, and the file is complete. Then the Particle Swarm Optimization algorithm itself.
Now the optimization algorithm. PSO function LCOH receives parameters, data, penalty coefficients, and seed for randomization. The output is a structure out containing the best solution. Comment, Particle Swarm Optimization for PLTS and inverter capacity pairs with minimum LCOH. Continuous particle positions are mapped to discrete grid before evaluation. Equation 3,27. If provided, RNG sets the randomizer so the results can be reproduced. PSO settings are taken from partik PSO to short variable O. LB is the lower bound of the two variables. PLTS capacity and inverter capacity. UB is the upper bound. Maximum particle speed, 30% of the range width. Comment, Mapping to grid capacity. Anonymous GPV function, rounding the PV capacity to multiples of one module, then clamping it between the lower and upper bounds. Anonymous GINF function, rounding the inverter capacity to multiples of 1 kW and clamping it within the bounds. Grid combines both to map one particle position to a grid point. Initialization Section Initial X position, uniformly random within the bounds, 1 row per particle, 2 columns. Initial velocity V0 PB stores the best position of each particle, and FPB is its fitness value. Initially infinite. Best is the best position of the entire swarm, and FG is its fitness. History will store the best fitness at each iteration. Trace stores the positions of all particles at each iteration, for plotting later. Counter for iterations without improvement, and counter for evaluation count. Main log of iterations from 1 to maximum iterations. Evaluation phase For each particle, Place its position on the grid, And calculate fitness with the LCOH fitness function. Increment the evaluation counter. If the fitness is better than the particle's personal record, Update FPB and PB. If better than the swarm's record, With a very small tolerance. Update FG and Best, And zero the counter without improvement. Close the low branch Close the low particle Record the best fitness of this iteration. Save the position of all particles at this iteration. Add the counter without improvement. If already 30 iterations without improvement, Stop the low with break. Stage of velocity and position update. Equation 3.28, Inertia weight decreases linearly from initial to final value. Two matrices of random numbers R1 and R2. Equation of velocity PSO, Weight multiplied by the old velocity, Plus attraction to the personal best position, Plus attraction to the swarm's best position. Limit velocity to not exceed maximum velocity. New position is the old position plus velocity, Constrained within the search space boundaries. Close the low iteration. Re-evaluate the best position to get the detailed results, Without penalty. Save the optimal capacity of PLTS and inverter to output. Save LCOH in rupiah and dollars. Save feasible status and detailed results. Trim history and trace until the last correctly executed iteration. Save the number of iterations and evaluations. Closing function. Save with Ctrl+S and the file is done.
Step 3 script to run PSO and plot the results.
Step 3 script. Running PSO optimization for PV plant capacity and inverter. Clear variables, set graphics style, and load parameters. Load the PV data saved in step 1. Penalty coefficient is 10 times LCOH scenario 2. How to calculate it. Call calculate system without PV with grid source, then take the LCOH RP field. Start stopwatch to measure computation time. Run 1 time PSO with SIP 1. Print computation time, read by TOG, and number of evaluations. Print optimal PV plant capacity and number of modules. Print optimal inverter capacity and DC-AC ratio. Print optimal LCOH in dollars per kilogram. Save PSO results to PSO 1.mart for comparison with grid set. Plot section, convergence, and particle distribution. Create a graphics window. Split the window into 2 panels. Switch to the first panel. Best fitness history plot, converted to dollars per kilogram. X and Y axis labels. First subplot title, and Y-axis limits from 7.2 to 9. Move to the second subplot, hold on. T is the number of iterations performed, from the size of the third trace. Top plot for 3 iterations. Start, one-third, and end. Scatter plots the positions of all particles at that iteration. Closing lob. Yellow star marks the optimal position. Axis labels, PV plant capacity, and inverter capacity. Legend for 3 iterations and the optimum. Sprint inserts the iteration number. Second subplot title, save the plot as VIK 03. Save with Ctrl S, and the file is done.
We click run. Only 0.2 seconds, PV plant 67.76 kW peak, or 121 modules, inverter 46 kW, DC to AC ratio 1.47, and LCOH 7.286 dollars per kilogram.
Convergence and particle scatter plots appear. On the left plot, the best fitness drops quickly and then converges.
On the right, particles that were initially spread out eventually cluster at the bottom-left corner, which is the constraint boundary of effective hours and DC to AC ratio. For validation, we write the exhaust TV grid search function.
Function X LCOH performs exhaust TV grid search, evaluating all combinations of PV plant capacities, step 1 module, and inverter, step 1 kW. Vector of all possible PV plant capacities, from lower to upper bounds with step 1 module. Created column with transpose. Vector of all inverter capacities with step 1 kW. Na and Nb are the number of elements for each factor. The lecoh matrix is filled, i.e., not numbers. Only the VAS Cible points will be filled later. The VAS logic matrix is used to record the VAS Cible points. Outer loop over all PV plant capacities. Inner loop over all inverter capacities. Calculate the system for this combination. Note whether VAS Cible is achieved. If VAS Cible is achieved, save the lecoh. Close both loops. Min over the entire matrix, ignoring NAN, and gives the lowest lecoh with its index. IND 2 sub converts the single index into row and column numbers. Save the capacity vector, lecoh matrix, and VAS Cible matrix as output. PV plant and inverter capacities at the optimal point. Optimal lecoh in rupiah and dollars. Total number of combinations, and the number of VAS Cible, calculated with NNZ. Close the function. Save with Ctrl S, and the file is done.
Step 4 script, comparing PSO with grid search.
Step 4 script, validating PSO results with exhaustive TV grid search. Clear, set graphic style, and load parameters. Load PV data and PSO results from step 3. Start stopwatch. Run grid search over all combinations. Print the time duration of grid search. Print the total number of combinations and the VAS Cible. Print the optimum according to grid search. Print the optimum according to PSO, for comparison. Equation 3.29. Relative difference of LCOH PSO compared to grid search, in percent. Print that difference. Save the grid search results. Image section, map of LCOH in the search space. Create a graphics window. Split into two subplots. First subplot, hold on. Matrix Z, LCOH in dollars, with transpose so that the capacity of the PV plant is on the X-axis. Images draw the color map. Non-VAS Cible points are made transparent through alpha data. Y-axis direction is reversed normal, and gray background for areas that violate constraints. Color scale parula is reversed, and color bar is labeled. Color scale limits, from the lowest LCOH up to the lowest plus 1.5. Yellow star marks the grid search optimum. Red circle marks the PSO optimum. Axis limits to zoom in on the interesting area. Axis labels. Legend. Title of the first map. Second map, LCOH slice. Find the index of the PV plant capacity closest to the optimum. Plot LCOH against inverter capacity at the optimal PV plant capacity. Mark the optimal point. Set axis limits and labels. Title, with the inserted PV plant capacity. Save the graph as VIK 04.
Save with Ctrl S, and the file is done.
Click Run. Grid search takes about 9 seconds. Only 39,000 of 194,000 combinations are visible. The grid search optimum is exactly the same as PSO, 67.76 kW peak, 46 kW, difference 0%. The LCOH map appears.
The LCOH map shows the visible region in a corridor shape, and cost increases towards the upper right.
The optimum is at the lower left corner. The intersection on the right shows that increasing inverter capacity only increases LCOH. Step 5 script, test stability with 30 runs. Step 5 script, test PSO stability with 30 independent runs.
Clean up, set graph style, load parameters, load PV data, penalty coefficient from step 3, and grid search results as reference. N is the number of runs, 30. Prepare an empty vector to hold results for each run. Loop over all runs. Run PSO with different seeds for each run, that is, 100 plus run number. Save PV plant capacity, inverter capacity, LCOH, and number of iterations. End loop. Print the title of the statistical table. Statistics for PV plant capacity, minimum, maximum, average, and standard deviation. Statistics for inverter capacity. Statistics for LCOH. Equation 3.30, coefficient of variation, which is standard deviation divided by average, in percent. Print the coefficient of variation. Calculate how many runs are needed to reach the optimal grid search. Save the results of multi-run. Chart section. Create a graphical window. One row with three subplots. First subplot, LCOH per run. Dashed reference line, which is LCOH grid search. Labels and title for the first subplot. Second subplot, PV plant capacity per run. Reference line grid search. Labels and title. Third subplot, inverter capacity per run. Reference line grid search. Labels and title. Save the chart as fit 05. Save with Ctrl+S, and the file is complete.
Click run. 30 times PSO with different seeds. 28 out of 30 runs are exactly at the optimal grid search, and the LCOH coefficient of variation is only 0.01%.
The results graph of 30 runs appears.
PV Plant capacity is always the same. The simulation stops at the 47 kW inverter with LCOH only 0.03% higher. PSO is consistent, but does not guarantee the global optimum, so grid search validation remains important. Script step six, scenario comparison and operational profile.
Script step six, comparing scenarios one to four and plotting the operational profile. Clean, format, and load parameters. Load PV data, three reference scenarios from step two, and grid results. Scenario four, calculate the system at the optimal capacity resulting from the optimization. Combine the four scenarios into one cell array. SC is the column version of the array cell. The name of the fourth scenario for table and graph labels. Create table. First column is the scenario name, then the capacity of the PV plant and inverter, taken with a cell phone from each scenario. Add the capex column in millions of rupiah. Annual operation column in millions of rupiah. Grid energy column in megawatt hours. Column number of hrc. Solar fraction column. Cost column in dollars per kilogram. Name the first three columns. Display the table in the command window. Save the table to a CSV file. Print the difference in LCOH between scenario 4 and scenario 2, in dollars and percent. Print the cost savings scenario 4 compared to the previous research design, scenario 3. Save scenario 4 and table. Figure 6. LCOH composition. Create a plot window. Arrange the LCOH components matrix, 4 scenarios x 5 components. In scenario 1, all LCOH is electricity cost, so fill it into the electricity column. A bar chart with a staked type bar draws a stacked bar chart. Arrange the 5 component colors from the palette. Lob colors each component. Scenario names on the X-axis. Y-axis label and axis limits. Legend of the 5 cost components, placed above the graph. Write the total LCOH value above each bar. Graph title. Save as VIK 06. Figure 7. Profiles of sunny and cloudy days. Find the day number with the maximum and the day with the minimum. Create a plot window. Two adjacent subplots. Lob for 2 days. Select a day, then calculate the 24-hour index of that day on the 8760-hour series. Move to the next subplot, hold on. Area plot for PV power to load and grid power as stacked areas. Color green for PV and gray for grid. Orange dashed line, available PV power. 40 kW load line, and X-axis limit. X-axis label. Two plot titles. Plot title with day number. Legend only on the first plot. Close lob. Save as VIK 07. Save with Ctrl S, and the file is done.
Click Run. The comparison table of four scenarios appears in the command window. LCOH for scenario 47,29 dollars per kilogram. Cheaper by 2.3 percent compared to the previous research design. But still 1.5 percent above grid plus REC without PLTS.
Two graphs appear.
The largest cost remains grid electricity. Blue bars are the CAPEX of PLTS and inverter. Which is smaller in scenario 4 compared to scenario 3. On sunny days, the load is fully supplied by PLTS during effective hours and excess power is wasted.
On the darkest day, almost the entire load is met by grid and purchased REC. One more helper function, find optimum underscore, for sensitivity analysis. The find optimum function runs PSO with several seats and takes the best one.
Used for sensitivity and assumption testing, to ensure results are not dependent on a single seat. If no seat list is provided, the default seats are 1 to 3. Calculate penalty coefficient, 10 times LCOH of scenario 2. Start with an empty best solution. Select the top seat. Run PSO with that seat. Replace the best solution if still empty, or if the new result is feasible and cheaper, or if the old solution is not feasible. Save the new result. Close the branch and top. Close the function. Save with Ctrl + S, and the file is done.
Step 7 script, sensitivity analysis and break-even point.
Step 7 script, sensitivity analysis and break-even point. PSO is run again at each point. Clean, set style, and load basic parameters as par 0. Load PV data. Comment, parameters that are varied. First variation, capex factor from 0.5 to 1.4 with step 0.1. Saved as a structure containing name, value, and unit. Second variation, grid tariff from 800 to 2,000 rupiah per kilowatt hour, step 150. Third variation, REC price from 0 to 150,000 rupiah per megawatt hour. Prepare a cell array to store the results of the three variations. Top over the three types of variations. Number of points, and result matrix with columns. Values, PV plant, inverter, leco scenario 4, and leco scenario 2. Top over each value. Set basic parameters, and take variation values. Switch to select the parameter to be changed. Case 1, capex module, inverter price, and O&M cost multiplied by a factor. Case 2, grid tariff is replaced. Case 3, REC price is replaced. Close switch. Find the optimum using PSO 3 seed on the changed parameters. Calculate LCOH scenario 2 on the same parameters. Save one row of results. Close loop value. Save all variation results. Equation 3.31. Difference between LCOH scenario 4 and scenario 2. Break-even point is when the difference is 0. Find the first index where the sign of the difference changes. If the sign does not change, break-even point is not found, and it is filled in. If it changes, break-even point is calculated using linear interpolation. Close conditional branch. Print the break-even point of this variation. Save the break-even point to the structure. Close variation loop. Save sensitivity results. Image section. Format numbers for the break-even point label on each graph. Create a graph window. 3 parallel subplots. Top row with 3 variations. Next subplot, and take the results of the variations. Blue line. LCOH scenario 4. Gray line. LCOH scenario 2. If the break-even point exists, draw a red dashed vertical line along with its label. End of if-branch. Axis labels. Legend only on the first subplot. End of loop. Save as Vick 08.
Save with Ctrl S, and the file is complete. Click Run.
Investment cost, grid tariff, and REC price are varied one by one, and PSO is run again at each point. The process takes about half a minute The video is sped up. The result is, the break-even capex is 0.949 times, tariff Rp1.178, and REC Rp109.000.
The sensitivity graph appears.
The blue line is scenario 4,
and the gray line is scenario 2.
The break-even point is marked by the red dashed line,
capex must decrease by about 5%, or the grid tariff increases to Rp1.178 per kWh, or the REC price reaches Rp109.000 per MWh. Script step 8, test supporting assumptions.
Script step 8, test supporting assumptions. Clean up, set style, load basic parameters, load PV data. Comment, each line contains the assumption name and the parameter change function. Start with an empty array, Three DC to asem maximum ratios tests, 1.2, Base value 1.5, and 2.0. Anonymous function set field changes one parameter field. Two clear day percentage tests, 10% and 50%. Wider effective hour test, 9-15, 6 hours. Two discount rate tests, 6% and 12%. Two inverter price tests, 40 and 120 dollars per kWh. Local function changes INVE at the end of the file changes inverter cost. Inverter replacement test earlier, on year 10. Number of tests and result matrix. Loh break all tests. Apply the transformation function on the base parameters. Copy PV data. If the clear day percentage changes, re-calculate PIFGIS data with the new clear day. Find optimum with PSO 3SIP. Calculate LCOH scenario 2 on the same parameters. Save one row of results, capacity, LCOH, and the difference compared to scenario 2. Print this test result. Close tab. Arrange the results table. Name the columns. Save the table to CSV. Image section. Create a graphics window. Draw a horizontal bar chart for LCOH ready assumption, with the assumption name on the Y-axis. X-axis label, title, and axis limits. Save as VIK09. Local function change INVE accepts parameters and inverter price in dollars. Save the inverter price and conversion to rupiah. Module cost is recalculated so that the total system cost remains according to equation 3.13. Close the local function.
Save with Ctrl S, and the file is done. Click Run.
Eleven assumption tests are run, each with PSO 3SID. If the DC to AC ratio can be 2, the inverter is sufficient at 40 kW, same as the load. A wider effective hour range increases the PV plant to 83 kW-pik. At a 6% discount rate, the PV plant becomes cheaper than the grid.
The most sensitive factors are the discount rate and the effective hour range. Inverter cost has almost no effect because the inverter is small. Finally, the wrapper script runs all steps sequentially.
Finally, the wrapper script runs all. Comments explain that, each script calls clear, so it is called directly without log variables. Run step 1 and 2. Disk prints a marker, then the script name is called. Steps 3 and 4, PSO and grid search. Step 5 and 6, stability test and scenario comparison. Step 7 and 8, sensitivity and assumption test.
Save with Ctrl S, and file is done. Summary of results, Optimal PV plant 67.76 kW peak and inverter 46 kW with LCOH 7.29 dollars per kilogram. PSO and grid search produce the same solution. Conclusion for thesis, inverter does not need to be large, just above the load, and limited by DC to AC ratio 1.5. This configuration is cheaper than the previous design, and will be more economical than grid plus REC if Capex drops around 5%. That is the steps to determine the optimal capacity of PV plant and inverter in MATLAB from empty project to results. All scripts, data, results, and report are available in the project folder. Thank you for watching. Need help with modeling and optimization using MATLAB? Cerdas Inovasi Digital offers MATLAB courses, modeling and optimization services for theses, dissertations, and industry, as well as providing project files from this tutorial. Contact us via WhatsApp, or visit cerdasinovasidigital.com.
Type a question or keyword; we find the part of this episode that explains it and jump the video there.
Notes are saved with the current video time and are only visible to you.
Stuck on a step? Ask here; the instructor and other learners can answer.
No questions yet.

Cerdas Inovasi Digital Team
Software developers, BIM & 3D engineers, and AI practitioners
We build software, BIM models, games and AI automations for clients every day, and turn that hands-on work into step-by-step classes: every step is shown on screen and comes with a PDF guide you can keep.
See our clients →