I. Coding Standards
**Variable Naming**
- Variable names should use camelCase, with the first word in lowercase and subsequent words starting with uppercase letters.
Example: velocity, angularAcceleration. - Variables with a broad scope should have meaningful names.
Variables with a smaller scope can use short names.
Example: x, y, z - The prefix n should be used for variables representing the quantity of objects.
Example: nFiles, nCars, nLines - Plural form conventions
Example: point, pointArray - Variables representing the number of a single entity can end with the suffix No.
Example: tableNo, employeeNo - Iterator variables should be named with i, j, k, etc., or use them as prefixes.
iFiles, jColumns - For nested loops, iterators should be arranged in alphabetical order and provided with meaningful names.
for iFiles = 1:nFiles
for jPositions = 1:nPositions
...
end
end
- Avoid using negated Boolean variable names
Use isFound instead of isNotFound - Acronyms, even if typically uppercase, should be mixed or lowercase.
html, isUsaSpecific - Avoid using keywords or special value names
**Constants**
- Constant names should be all uppercase, with underscores separating words.
MAX_ITERATIONS, COLOR_RED - Constants can use general type names as prefixes.
COLOR_RED, COLOR_GREEN, COLOR_BLUE
**Structures**
- Structure names should use PascalCase, with the first letter of each word capitalized.
Example: Car, DumpTruck - Do not include the structure name in field names.
Use Segment.length instead of Segment.segmentLength
**Functions**
- Function names should document their usage and can be in lowercase or mixed case.
width(), computeTotalWidth() - Functions should use meaningful names, such as computeTotalWidth instead of compwid
- Functions with a single output can be named based on the output
Example: shearStress(), standardError() - Functions with no output parameters or those returning only handles should be named based on their functionality.
Example: plotfft() - Reserve prefixes get/set for accessing objects or properties.
Example: getobj(), setappdata() - Reserve the prefix compute for methods that calculate something.
Example: computeSumOfResiduals(), computeSpread() - Reserve the prefix find for methods that search for content.
Example: findOldestRecord() - Reserve the prefix initialize for methods that instantiate objects or concepts.
Example: initializeProblemState() - Reserve the prefix is for Boolean functions.
Example: isCrazy, isNuts, isOffHisRocker - When creating meaningful names for closely related concepts or operations, it is best to use strongly related names, especially when one operation is the opposite or complementary to another.
Example: get/set,
add/remove, create/destroy, start/stop, insert/delete,
increment/decrement, old/new, begin/end, first/last, up/down, min/max,
next/previous, open/close, show/hide, suspend/resume, etc. - Pay attention to function name conflicts; use which -all or exist to check for function name shadowing.
**Files**
**M-files**
- Modularize code, using snippets to form the whole.
- Write functions that are easy to test.
- Clarify interactions. Use inputs and outputs instead of global variables. Use structures instead of long parameter lists.
- Partition. All subfunctions and most functions should do one thing well.
- Use existing functions whenever possible instead of custom coding functions.
- Move code blocks used in multiple m-files to functions.
- Use subfunctions when a function is called by only one other function.
- Write a test script for each function.
**Declarations**
**Variables and Constants**
- Variables should not be reused unless memory constraints require it.
- Related variables of the same type can be declared in a common statement. Unrelated variables should not be declared in the same statement.
persistent x, y, z - Document important variables in comments near the beginning of the file. Record constants with end-of-line comments.
THRESHOLD = 10; % Max noise level
**Global Variables**
Minimize the use of global variables and constants. Consider using functions instead of global constants.
**Loops**
- Variables used in loops should be initialized immediately before the loop.
result = zeros(nDays,1);
for iDay = 1:nDays
result(iDay) = foo(iDay);
end
-
Minimize the use of break and continue in loops.
-
End lines in nested loops can be commented to clarify code blocks.
for index=1:2
if index==1
dosomething(index); ...
end % End if
end % End for
**Conditional Statements**
- Avoid complex conditional expressions; use temporary logical variables instead.
isValid = (v >= lowerLimit) & (v <= upperLimit);
isNew = ismember(v, valueArray);
- Avoid using the conditional expression if 0.
- if-else sequences should include an else condition.
Usual cases should be placed in the if part, and exceptions in the if-else part. - switch statements should include an otherwise condition.
- Use switch sequences if the variable is a string.
- Use switch statements instead of multiple if-elseif-else statements whenever possible.
**Layout, Comments, and Documentation**
**Layout**
- Content should be kept within the first 80 columns.
- Lines should be split after commas, spaces, and operators.
- Continuation lines should be aligned with the start of the expression on the previous line
Example:
totalSum = a + b + c ...
d + e;
- Basic indentation should be 4 spaces.
- Generally, a line of code should contain only one executable statement.
- Short single-statement if, for, or while statements can be written on one line.
if (condition), statement; end
**Spaces**
- Insert spaces before and after =, &, and |.
- A comma should be followed by a space.
- Keywords should be followed by a space.
- Code blocks should be separated by three blank lines or section breaks.
- Use aligned code wherever it enhances readability.
**Comments**
- Comments should be consistent with the code but not repeat it.
- Comments should have the same indentation as the referenced statement.
- Traditional function header comments should support help and lookfor. In MATLAB, using help + function name prints the first continuous block of comments for that function.
- Use lookfor + function command to view an introduction to a function. Entering lookfor plot in the command window will display all M-files related to the plot function.
- Function header comments should discuss any special requirements for input/output parameters and describe any side effects of the function. Use correct capitalization for the function name in the header comment.
function runEverything
% runEverything runs all mfiles in its folder
- Place any copyright lines and change history after the function title, separated by a blank line.
- All comments should be in English.
**Documentation**
- Use text markup to write header comments, providing user documentation. Include sections corresponding to the help page: syntax, description, examples, and see also. Consider writing documentation first to better define inputs, outputs, and functionality.
- Consider using source code control tools like SVN or GIT. If not using source control tools, add change history comments after the function title or near the top of the script to record changes.
II. Algorithm Standards
Algorithms generally consist of four parts: the main algorithm file, associated function files, data files, and example files.
Main Algorithm File
The main algorithm file must provide a function that clearly defines input and output parameters and uses comments for explanation. Typically, the function name can be main. The main function should modularize the code to form a whole. When the computational logic is complex, the code block should be moved to a separate function.
% Function to calculate hourly power of photovoltaic panels
% Input parameters
% geoFilepath: GeoJSON file, calculate total area
% panelEfficiency: Photovoltaic panel efficiency 1*1
% shadingFactor: Shading impact factor (1*1, between 0-1)
% solarIntensityFile: Hourly solar intensity data file
% Output parameters
% hourlyPower: Hourly power 8760*1
function hourlyPower = main(geoFilepath, panelEfficiency, shadingFactor, solarIntensityFile)
data = load(solarIntensityFile); % Load solar data file
solarIntensityData = data(:, 5); % Take the 5th column from the file, get hourly solar intensity
if length(solarIntensityData) ~= 365 * 24
error('Data length mismatch: Requires hourly solar intensity data for one year (8760 rows).');
end
solarIntensityData = solarIntensityData / 1000; % Convert solar intensity units from wh to kwh
hourlyPower = zeros(length(solarIntensityData), 1); % Initialize return parameter, improve efficiency
panelArea = calculateTotalArea(geoFilepath); % Call area calculation function, input geo area file path, output area value
for hour = 1:length(solarIntensityData)
currentSunIntensity = solarIntensityData(hour);
currentSunIntensityWatt = currentSunIntensity * 1000;
effectiveSunIntensity = currentSunIntensityWatt * (1 - shadingFactor);
hourlyPower(hour) = panelArea * panelEfficiency * effectiveSunIntensity;
end % Loop to calculate hourly photovoltaic panel power
end
Associated Function Files
The area calculation function calculateTotalArea() called in the main function
% Calculate area
% filepath: Modeling exported area file path
% totalArea: Area 1*1
function totalArea = calculateTotalArea(filepath)
fid = fopen(filepath, 'r');
raw = fread(fid, inf);
str = char(raw');
fclose(fid);
data = jsondecode(str);
totalArea = 0;
for i = 1:length(data.features)
if isfield(data.features(i).properties, 'Area')
totalArea = totalArea + data.features(i).properties.Area;
end
end
end
Data Files
Data files are generally in .mat or .dat format, opened as follows
Example Files
Example files mainly show how to call various functions. In theory, each function should have a test script, but in actual development, only the main function and complex functions need to provide test scripts.
% Sample script to demonstrate execution of function hourlyPower = main(geoFilepath, panelEfficiency, shadingFactor, solarIntensityFile)
geoFilepath = 'C:\Users\xiao\Downloads\measurements.geojson';
panelEfficiency = 0.2089; % Monocrystalline silicon
shadingFactor = 0.2; % Shading factor
solarIntensityFile = 'zhoushangang-hour.dat';
hourlyPower = main(geoFilepath, panelEfficiency, shadingFactor, solarIntensityFile);
disp(hourlyPower);
III. Algorithm Compilation
Compiled algorithms can be called on other platforms. Currently, the common method in our project is jar package calling, so a brief introduction to the packaging method is provided to test if the written algorithm works correctly.
Compilation Environment Installation
Official documentation: https://ww2.mathworks.cn/help/compiler_sdk/java/configure-your-java-environment.html
Before compiling, install Java JDK and add environment variables. Add JAVA_HOME in the environment variables and check for special characters in comments.
Compilation Files
Official documentation: https://ww2.mathworks.cn/help/compiler_sdk/gs/create-a-java-application-with-matlab-code.html
Find LibraryCompiler under APP and enter the compilation interface
Add the main function file in the compilation interface, select Java Package
Add the test file, modify the class name, and click Package to package
If the code has no issues, a prompt indicating packaging completion will appear directly