MATLAB uses Pre-Matlab algorithm writing specifications

I. Coding Standards

**Variable Naming**

  1. Variable names should use camelCase, with the first word in lowercase and subsequent words starting with uppercase letters.
    Example: velocity, angularAcceleration.
  2. Variables with a broad scope should have meaningful names.
    Variables with a smaller scope can use short names.
    Example: x, y, z
  3. The prefix n should be used for variables representing the quantity of objects.
    Example: nFiles, nCars, nLines
  4. Plural form conventions
    Example: point, pointArray
  5. Variables representing the number of a single entity can end with the suffix No.
    Example: tableNo, employeeNo
  6. Iterator variables should be named with i, j, k, etc., or use them as prefixes.
    iFiles, jColumns
  7. 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
  1. Avoid using negated Boolean variable names
    Use isFound instead of isNotFound
  2. Acronyms, even if typically uppercase, should be mixed or lowercase.
    html, isUsaSpecific
  3. Avoid using keywords or special value names

**Constants**

  1. Constant names should be all uppercase, with underscores separating words.
    MAX_ITERATIONS, COLOR_RED
  2. Constants can use general type names as prefixes.
    COLOR_RED, COLOR_GREEN, COLOR_BLUE

**Structures**

  1. Structure names should use PascalCase, with the first letter of each word capitalized.
    Example: Car, DumpTruck
  2. Do not include the structure name in field names.
    Use Segment.length instead of Segment.segmentLength

**Functions**

  1. Function names should document their usage and can be in lowercase or mixed case.
    width(), computeTotalWidth()
  2. Functions should use meaningful names, such as computeTotalWidth instead of compwid
  3. Functions with a single output can be named based on the output
    Example: shearStress(), standardError()
  4. Functions with no output parameters or those returning only handles should be named based on their functionality.
    Example: plotfft()
  5. Reserve prefixes get/set for accessing objects or properties.
    Example: getobj(), setappdata()
  6. Reserve the prefix compute for methods that calculate something.
    Example: computeSumOfResiduals(), computeSpread()
  7. Reserve the prefix find for methods that search for content.
    Example: findOldestRecord()
  8. Reserve the prefix initialize for methods that instantiate objects or concepts.
    Example: initializeProblemState()
  9. Reserve the prefix is for Boolean functions.
    Example: isCrazy, isNuts, isOffHisRocker
  10. 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.
  11. Pay attention to function name conflicts; use which -all or exist to check for function name shadowing.

**Files**

**M-files**

  1. Modularize code, using snippets to form the whole.
  2. Write functions that are easy to test.
  3. Clarify interactions. Use inputs and outputs instead of global variables. Use structures instead of long parameter lists.
  4. Partition. All subfunctions and most functions should do one thing well.
  5. Use existing functions whenever possible instead of custom coding functions.
  6. Move code blocks used in multiple m-files to functions.
  7. Use subfunctions when a function is called by only one other function.
  8. Write a test script for each function.

**Declarations**

**Variables and Constants**

  1. Variables should not be reused unless memory constraints require it.
  2. 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
  3. 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**

  1. Variables used in loops should be initialized immediately before the loop.
result = zeros(nDays,1);

for iDay = 1:nDays

 result(iDay) = foo(iDay);

end
  1. Minimize the use of break and continue in loops.

  2. 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**

  1. Avoid complex conditional expressions; use temporary logical variables instead.
isValid = (v >= lowerLimit) & (v <= upperLimit); 
isNew = ismember(v, valueArray);
  1. Avoid using the conditional expression if 0.
  2. if-else sequences should include an else condition.
    Usual cases should be placed in the if part, and exceptions in the if-else part.
  3. switch statements should include an otherwise condition.
  4. Use switch sequences if the variable is a string.
  5. Use switch statements instead of multiple if-elseif-else statements whenever possible.

**Layout, Comments, and Documentation**

**Layout**

  1. Content should be kept within the first 80 columns.
  2. Lines should be split after commas, spaces, and operators.
  3. Continuation lines should be aligned with the start of the expression on the previous line

Example:

totalSum = a + b + c ... 
           d + e;
  1. Basic indentation should be 4 spaces.
  2. Generally, a line of code should contain only one executable statement.
  3. Short single-statement if, for, or while statements can be written on one line.
if (condition), statement; end

**Spaces**

  1. Insert spaces before and after =, &, and |.
  2. A comma should be followed by a space.
  3. Keywords should be followed by a space.
  4. Code blocks should be separated by three blank lines or section breaks.
  5. Use aligned code wherever it enhances readability.

**Comments**

  1. Comments should be consistent with the code but not repeat it.
  2. Comments should have the same indentation as the referenced statement.
  3. 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.

  1. 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.

  1. 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
  1. Place any copyright lines and change history after the function title, separated by a blank line.
  2. All comments should be in English.

**Documentation**

  1. 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.
  2. 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

By Tim

Leave a Reply

Your email address will not be published. Required fields are marked *