Memuat
Memuat
Want to go deeper?
Join one of our courses or ask us directly on WhatsApp.
Picked from the software, topic, and level of “Class MATLAB: MATLAB Tutorial: Water Cycle Algorithm (WCA) for Hybrid Microgrid Optimization”.
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.
This is the result we will get, the WCA convergence curve and flow distribution, as well as a 30s stability test with a variation coefficient of only 0.31 percent. Let's start from a blank project. Hello, welcome. In this video, we will learn the Water Cycle Algorithm, or WCA, in MATLAB, to determine the number of solar panels, wind turbines, batteries, and diesel generators in a hybrid microgrid. All work is done from scratch, from a blank project, writing all code line by line, running the optimization, until testing stability and the effect of population size. The background is as follows. A hybrid microgrid consists of solar panels, wind turbines, batteries, and diesel. The question is, how many units of each component, so that energy cost, supply loss, and wasted power are all as low as possible? WCA answers this by mimicking the water cycle. Many flows, which are candidate solutions, flow towards rivers, and rivers flow towards the sea, which is the best solution. Flows that are too close to the sea evaporate, then are regenerated at a random location. Our algorithm settings are taken from the wca.m file in the research folder. 50 iterations, 20 flows, a step coefficient between 1 and 2, and an evaporation distance of 0.1. There are 4 decision variables with their bounds. Solar panels 100-2000, wind turbines 1-20, batteries 10-500, and diesel 1-5. Objective function weights 0.4 for energy cost, 0.599 for supply loss, and 0.001 for dummy load. The workflow has 3 stages. Each stage is 1 MATLAB script, and all of them use the same 5 core functions. Parameters, objective function, population generator, fitness calculator, and WCA algorithm. All these files will be typed from scratch from the beginning. The objective function combines 3 aspects. Energy cost increases with the number of components. The probability of supply loss decreases as total capacity increases. And dummy load appears when generation exceeds battery capacity. This is a simplified model for learning the algorithm, not a full hourly simulation.
We start from scratch. This is a newly opened MATLAB session. The current working folder is still the home folder, and our project has not been created yet.
In the address bar, we navigate to the WCA project folder, which is still empty.
We create three project folders using the mcdir command via the cell phone. 02 matlab for the program, 03 results, and 04 images. Notice the files panel, the three folders appear immediately. The CD20 MATLAB command moves the working folder to the program folder. We are ready to write code. Now we start writing the program from an empty file. First, a helper function for the graph style. In the command window, we type edit gaya underscore gambar. MATLAB asks if a new file should be created. We click yes.
We start with the helper function for the graph style. The first line declares the gaya gambar function without inputs, with one output named C, which is the color palette. This comment line explains the function's purpose, sets up the graph display to be consistent, and returns 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 type becomes Arial. The default axis font size becomes 11. The font type for text, such as titles and labels, also becomes Arial. The box around the axes is turned off to make the display cleaner. Set the x-axis line width to 0.8, and the default plot line width to 1.8. Turn on the grid lines for the x and y axes, with a thin transparency of 0.15 to avoid disturbing the data. The next seven lines define the color palette as fill for the C structure. Blue, orange, green, red, purple, gray, and yellow. Each color is a 3-number vector 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, which receives the window name as well as width and height in pixels, and returns the figure handle.
The comment explains, creating a 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 of width by height, as well as a white background color. Move GUI 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, receives figure, parameter structure, 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 from the name plus a dot PNG, with a resolution of 220 DPI. Closing function.
Save with Ctrl S, and the file is complete. Now the parameter file. All algorithm settings and variable limits are collected here.
We start with the parameter file. Declaration of the WCA parameter function with no input and one output, which is the structure PAR. All numerical settings of the algorithm are collected in one place, so they can be easily changed without touching the algorithm code. Comment title section, Folder Project. File name with the full path option provides the complete file location, and file parts take the parent folder, which is 0.2 matlab. Go up one level to get the root project folder. From there, two folder addresses are organized, 0.3 results for output data, and 0.4 images for graphics. In this way, the project can be moved to another computer without changing the addresses. Section of Water Cycle Algorithm settings, maximum iterations 50, and population size 20 flows. Each flow is one candidate configuration of the microgrid. Part point C is the range of step coefficient, between 1 to 2, and dmax is the minimum distance 0.1. Flows that are too close to the sea will evaporate and be regenerated. Print switch determines whether progress at each iteration is displayed in the command window. We will later turn it off when running multiple runs. Decision Variable Section There are 4. Number of solar panels, wind turbines, batteries, and diesel generators, their names are stored in a cell array. Matrix Bones contains the lower and upper bounds of each variable, one row per variable, separated by semicolons. Solar panel 100 to 2000, wind turbine 1 to 20, battery 10 to 500, and diesel 1 to 5 units. The number of variables is automatically taken from the number of rows of Bones with the size function. Last, the objective function weight, 0.4 for energy cost COI, 0.599 for probability of supply loss LPSP, and 0.001 for dummy load. The number is 1. And N closes the function.
Save with Ctrl S, and the file is done. Next, the objective function, which is the size of how good or bad one microgrid configuration is.
Now the heart of the problem, the objective function. Objective functions receive one configuration X and parameter structure, then return the combined cost value F, as well as the three components in com. The smaller, the better. We name the four elements of the vector X with easy-to-read names. Number of PV, wind turbine, battery, and diesel. COI, energy cost, is calculated from the cost per unit of each component. 0.2 for PV, 0.5 for turbine, 0.3 for battery, and 0.4 for diesel, divided by one thousand. LPSP is modeled to decrease as total capacity increases. The max function with 0 ensures its value never becomes negative. Dummy load, which is the excess power that is wasted. One-tenth of PV plus turbine, minus the battery capacity that can be stored, and also cannot be negative. The objective function is the weighted sum of the three components, using three weights lambda from the parameter structure. The three components are packed into the vector COM so that it can be reported later, then N closes the function. Remember, this is a simplified model for learning the algorithm, not a complete hour-by-hour simulation.
Save with Ctrl S, and file is done.
We test in command window by typing parsama
with parameter underscore WCA.
Matlab displays all settings as a structure. Then partitik bones displays the boundaries of four variables, solar panel 100-2000, wind turbine 1-20, battery 10-500, and diesel 1-5. Now test the objective function.
configuration 1000 solar panels,
10 wind turbines,
250 batteries,
and 3 diesel generating fitness around 0.70. Then configuration 100, 1, 10.1, and 1, which we expect to be optimal, generating fitness 0.6079,
a bit lower. And vector COM shows its three components, energy cost, LPSP, and dummy load. Helper function to generate the initial population.
Next helper function, create population, generate initial flow. Input parameter structure, output population matrix. Run creates a random matrix between 0 and 1, size is number of flows times number of variables. For loop per variable, random numbers are scaled to the actual range, that is, lower bound plus random times the difference between upper and lower bounds. Thus, each flow is guaranteed to be within the bounds. End of function.
Save with Ctrl S, and file is done. Helper function to calculate fitness for the entire population.
Helper function calculate fitness calculates the objective function value for the entire population rows at once. Array Fun calls the objective function for each row from 1 to number of rows, and the results are collected into 1 fitness vector. End of function. Save with Ctrl S,
and file is done.
We test both. The generated population has a size of 20 rows by 4 columns
20 flows with 4 variables
Then calculate underscore fitness resulting in 20 fitness values
and the lowest value is our initial sea candidate Now the most important part the water cycle algorithm itself
Now the algorithm itself WCA optimization The output is 5 Sea or best solution fitness value convergence history initial population and final population The idea mimics the water cycle flow flows into the river river flows into the sea and the sea is the best solution Lower and upper bounds are taken from matrix bones then transposed into a row vector with quotes Initial population is generated and its copy is saved in the initial variable for future plotting Fitness of all initial flows is calculated The flow with the lowest fitness becomes the sea Min returns the value and its index and the sea is taken from the row with that index. River is one quarter of the best flow, which has a fitness below the 25th percentile. The history factor is prepared to record the best fitness per iteration. The main loop runs for the maximum number of iterations. Inside it, the second loop checks each flow one by one. Only normal flows move, which are neither rivers nor seas. Eastmember with the rows option checks if the row is included in the river. Flow selects a target at random, with a 50% chance of flowing to one of the randomly selected rivers, otherwise directly to the sea. The random step coefficient is taken from the range C, between 1 and 2. Core equation of WCA, new position equals old position plus random times coefficient C times distance to target. One improvement from the initial code, position is clipped into the bounds with min and max, so that the flow does not go out of the reasonable capacity range. Closing the if branch and the flow loop. Evaporation stage. For each flow, if the distance to the sea is less than demex, and it is not the sea itself, then the flow is considered to evaporate. Second improvement, the sea is not deleted, so the best solution is not lost. The evaporated flow is regenerated at a new random position within the bounds, like rain falling back to the earth. Closing the if and evaporation loop. Fitness is recalculated for all flows, and the lowest value of this iteration is saved in F-Best. The sea is only updated if there is a better flow than the previous sea. In this way, the best fitness never deteriorates. The river is updated from a quarter of the new best flow. If by chance it is empty, the river is filled with the sea to avoid an error. The best fitness of this iteration is recorded in the history. If the print switch is on, print displays the iteration number and best fitness in the command window. Closing the main loop. The final population is saved to the final output, and end closes the function.
Save with Ctrl S, and the file is complete. We run the algorithm.
Progress of 50 iterations is displayed in the command window, The best fitness decreases and then stays.
Variable C contains the optimal solution,
and F-B is its fitness value. Then the first step script, P01 runs WCA, which runs WCA, validates the results, and draws the graph. Now the first step script,
which runs everything. Section titles start with 2 percent signs so they become sections in the editor. Clear variables, command window, and all old graphs. Call the color image style for the color palette, and WCA parameters for the entire settings. RNG with number 7 locks random numbers, so the results of this video can be repeated exactly the same. Tick and Tock measure computation time, among them we call WCA optimization with settings PAR. The optimal solution is displayed as a table with column titles as variable names, using a 2D table array. The objective function is called again the best solution to obtain all three components, then print the minimum fitness, time, and COI values, LPSP, and dummy load. Analytical validation section. Because each capacity increases the cost more Rather than the benefit of LPSP reduction, the theoretical optimum lies at the lower bound, except for the battery used to dampen the dummy load. Theoretical solution, PV and turbine at the bottom, tenth of a battery from PV plus turbine, and diesel at the lower bound. Theoretical solution fitness is calculated, then compared with the WCA results in percentage difference. The results are saved to the mat file in the 03 hasil folder. Image section. One figure contains two adjacent graphs, created with tileg layout one row two columns. First graph, convergence curve of the best fitness against iterations, dashed red line for theoretical value, as well as axis labels and title. Second graph, flow distribution on the plane of PV count and battery count. Gray for initial population, orange for final population, and yellow star for the sea. Axis labels, legend, title, and finally save the image by saving the figure as PNG in the 04 gambar folder.
Save with Ctrl S, and the file is done. We click run in the editor tab.
Optimal solution, 100 panels, 20 turbines, 10 batteries, and 1 diesel, with fitness 0,6136, only 0,93% above the theoretical optimum 0,6079. Computation time is less than 1 second. Two graphs appear in the middle of the screen,
and are automatically saved as PNG in the 04 gambar folder.
In the left graph, the best fitness drops sharply in a few iterations and then stabilizes. The red dashed line is the theoretical value. On the right, the initial population is spread out in gray, while the final population is clustered in the lower left corner, which is the location of the yellow star, that is, the sea. Step 2 script, test stability with 30 runs. Step 2 script,
test stability. Metaheuristic algorithms are random in nature, so a single run is not sufficient. We run it 30 times with different seeds. Start by clearing the workspace and setting up the style and parameters. The print switch is turned off to prevent the command window from being flooded with 30x50 lines. Number of runs is 30, and a vector F for fitness and a matrix X for solutions per run are prepared. Loop for 3,000 times. Each run uses the same seed as the run number via RNG, then the WCA optimization saves the solution and fitness. Summary statistics, best fitness, average, standard deviation, and coefficient of variation in percent. Average of each variable is displayed as a table and all results are saved to the mat file. Image section, two graphs side by side. First graph, final fitness histogram from 30 runs, to see the distribution. Second graph, each variable position is normalized over the range 0 to 1 relative to its bounds, so variables with different scales can be compared. Bar chart of average positions, plus bar error with standard deviation, variable names on the X-axis, as well as labels and title. Save as PNG.
Save with Ctrl S, and the file is done.
Click Run. 30 times WCA with different seeds. Best fitness 0,6079, same as theoretical optimum. Average is 0,6094, and the coefficient of variation is only 0,31%. Graphs of the 30 runs results appear.
Histogram shows two groups of results. A significant portion stops around 0,608, and a small part slightly higher, around 0.612. On the right, the solar panel and battery are almost always at the bottom, while the wind turbine and diesel vary, because their influence on fitness is very small. So WCA is consistent, but does not guarantee the global optimum in every run. Script step 3, the effect of population size. Script step 3,
the effect of population size. We compare the convergence speed for several population sizes. Initially the same as before. Clear, load style and parameters, turn off printing. Four population sizes. 10, 20, 40, and 80. Each size is repeated 15 times, and the matrix average holds the average convergence curve. Outer loop over population size. Every time, the pop size value in the parameter is changed. Inner loop 15 times with different seeds. Each run's history is divided by the number of iterations and summed up, so the result is the average. The average final fitness for each size is printed, and the outer loop is closed. The results are saved to the map file. For the image section, 1 graph, 4 curves, 1 for each population size. Axis labels, legend created with compose, title, and save as PNG.
Save with Ctrl + S, and the file is done.
Click run. Each population size is repeated 15 times, so the process takes about half a minute, and the video is accelerated. The average final fitness for the population after, 20, 40, and 80 respectively 0,6089, 0,6096, 0,6085, and 0,608.
A comparison graph appears.
The four curves are almost overlapping and all converge quickly.
Population 80 is the lowest, but population 10 is actually better than 20, so the effect is not monotonic and the difference is below 0.3%.
For this problem with 4 variables,
population 20 is already sufficient.
Summary of results, WCA finds a configuration that differs by only about 1% from the theoretical optimum, stabilizes in the 30s with a coefficient of variation of 0.31%, and is only slightly affected by population size. In conclusion, WCA is simple and fast for determining the size of microgrid components. We improved our original code with two aspects. The flow position is limited within a range, and the sea does not evaporate. Next step, replace this simplification objective function with an 8,760-hour simulation per hour as in the main research. That's the complete step-by-step process of implementing the Water Cycle Algorithm in MATLAB, from a blank project to the final results. All scripts, results, and reports 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 →