文章目录

  • 标识符命名规则
    • 一般变量
    • 常量、全局变量
    • 矩阵、结构体、元胞变量
    • 结构体属性构建及引用方式
    • 函数
  • 代码版式
    • 文件表头
    • 函数说明
    • 代码主体
      • 空行

标识符命名规则

一般变量

变量命名多采用小驼峰命名方式,如下

var serverForYou

循环变量多采用i,j,ki,j,ki,j,k等前缀形式命名,应避少用非前缀的命名方式,避免与matlab虚数单位重复

for i_population=1:K

常量、全局变量

常量或者全局变量均采用字母大写形式,如

DECISION

矩阵、结构体、元胞变量

矩阵,结构体及元胞变量多采用各类型英文名+"_"+变量实际代表含义名称,如

cell_mother
struct_population
matrix_fish

结构体属性构建及引用方式

构建


% state: optimization state of one generation
state = struct(...
'currentGen', 1,...         % current generation number
'evaluateCount', 0,...      % number of objective function evaluation
'totalTime', 0,...          % total time from the beginning
'firstFrontCount', 0,...    % individual number of first front
'frontCount', 0,...         % number of front
'avgEvalTime', 0 ...        % average evaluation time of objective function (current generation)
);

引用

options.popSize = 100;                   % populaion size
options.maxGen  = 150;                  % max generation 若此数值小于listbox值max,则不会显示options.numObj = 2;                     % number of objectives
options.numVar = 2;                     % number of design variables
options.numCons = 2;                    % number of constraints

函数

  1. 函数命名多采用小写字母+下划线分割形式命名
non_dominant_sort()
  1. get/set前缀多用来访问对象或者属性用
  2. compute前缀多用来计算某些量的函数用,如
compute_objectives()
  1. is前缀多用来判断
isbool()

代码版式

文件表头

样例

%___________________________________________________________________%
%  Multi-Objective Grey Wolf Optimizer (MOGWO)                      %
%  Source codes demo version 1.0                                    %
%                                                                   %
%  Developed in MATLAB R2011b(7.13)                                 %
%                                                                   %
%  Author and programmer: Seyedali Mirjalili                        %
%                                                                   %
%         e-Mail: ali.mirjalili@gmail.com                           %
%                 seyedali.mirjalili@griffithuni.edu.au             %
%                                                                   %
%       Homepage: http://www.alimirjalili.com                       %
%                                                                   %
%   Main paper:                                                     %
%                                                                   %
%    S. Mirjalili, S. Saremi, S. M. Mirjalili, L. Coelho,           %
%    Multi-objective grey wolf optimizer: A novel algorithm for     %
%    multi-criterion optimization, Expert Systems with Applications,%
%    in press, DOI: http://dx.doi.org/10.1016/j.eswa.2015.10.039    %       %
%                                                                   %
%___________________________________________________________________%

函数说明

样例1:

function [ 函数输出参数] = 函数名( 函数输入)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%此处为函数名,如果不是函数文件就取消此行
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%创建人:
%日期:
%修改人:
%日期:
%函数变量及功能的简单描述
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--函数主体

样例2:

function result = nsga2(opt, varargin)
% Function: result = nsga2(opt, varargin)
% Description: The main flowchart of of NSGA-II. Note:
%   All objectives must be minimization. If a objective is maximization, the
%   objective should be multipled by -1.
%
% Syntax:
%   result = nsga2(opt): 'opt' is generated by function nsgaopt().
%   result = nsga2(opt, param): 'param' can be any data type, it will be
%       pass to the objective function objfun().
%
%   Then ,the result structure can be pass to plotnsga to display the
%   population:  plotnsga(result);
%
% Parameters:
%   opt : A structure generated by funciton nsgaopt().
%   varargin : Additional parameter will be pass to the objective functions.
%       It can be any data type. For example, if you call: nsga2(opt, param),
%       then objfun would be called as objfun(x,param), in which, x is the
%       design variables vector.
% Return:
%   result : A structure contains optimization result.
%
%         LSSSSWC, NWPU
%   Revision: 1.2  Data: 2011-07-26
%*************************************************************************

样例3:

%NDSort - Do non-dominated sorting by efficient non-dominated sort.
%
%   FrontNo = NDSort(F,s) does non-dominated sorting on F, where F is the
%   matrix of objective values of a set of individuals, and s is the number
%   of individuals to be sorted at least. FrontNo(i) denotes the front
%   number of the i-th individual. The individuals have not been sorted are
%   assigned a front number of inf.
%
%   FrontNo = NDSort(F,C,s) does non-dominated sorting based on constrained
%   domination, where C is the matrix of constraint values of the
%   individuals. In this case, feasible solutions always dominate
%   infeasible solutions, and one infeasible solution dominates another
%   infeasible solution if the former has a smaller overall constraint
%   violation than the latter.
%
%   In particular, s = 1 indicates finding only the first non-dominated
%   front, s = size(F,1)/2 indicates sorting only half the population
%   (which is often used in the algorithm), and s = inf indicates sorting
%   the whole population.
%
%   [FrontNo,K] = NDSort(...) also returns the maximum front number besides
%   inf.
%
%   Example:
%       [FrontNo,MaxFNo] = NDSort(PopObj,1)
%       [FrontNo,MaxFNo] = NDSort(PopObj,PopCon,inf)%------------------------------- Reference --------------------------------
% [1] X. Zhang, Y. Tian, R. Cheng, and Y. Jin, An efficient approach to
% nondominated sorting for evolutionary multiobjective optimization, IEEE
% Transactions on Evolutionary Computation, 2015, 19(2): 201-213.
% [2] X. Zhang, Y. Tian, R. Cheng, and Y. Jin, A decision variable
% clustering based evolutionary algorithm for large-scale many-objective
% optimization, IEEE Transactions on Evolutionary Computation, 2018, 22(1):
% 97-112.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------

代码主体

空行

空行起着分割块或段落的作用,块(段落)之间一般留一个或两个空行。

空行使用规则:

逻辑块之间要留空行

%*************************************************************************
% 1. Initialization
%*************************************************************************
numObj = length( pop(1).obj );  % number of objectivesrefPoints = opt.refPoints;
refWeight = opt.refWeight;      % weight factor of objectives
if(isempty(refWeight))refWeight = ones(1, numObj);
end
epsilon = opt.refEpsilon;
numRefPoint = size(refPoints, 1);% Determine the normalized factors
bUseFrontMaxMin = false;    % bUseFrontMaxMin : If use the maximum and minimum value in the front as normalized factor.
if( strcmpi(opt.refUseNormDistance, 'ever') )% 1) Find possiable (not current population) maximum and minimum value%     of each objective.obj = vertcat(pop.obj);if( ~isfield(opt, 'refObjMax_tmp') )opt.refObjMax_tmp = max(obj);opt.refObjMin_tmp = min(obj);elseobjMax = max(obj);objMin = min(obj);for i = 1:numObjif(opt.refObjMax_tmp(i) < objMax(i))opt.refObjMax_tmp(i) = objMax(i);endif(opt.refObjMin_tmp(i) > objMin(i))opt.refObjMin_tmp(i) = objMin(i);endendclear objMax objMinendobjMaxMin = opt.refObjMax_tmp - opt.refObjMin_tmp;clear obj
elseif( strcmpi(opt.refUseNormDistance, 'front') )% 2) Do not use normalized Euclidean distance.bUseFrontMaxMin = true;
elseif( strcmpi(opt.refUseNormDistance, 'no') )% 3) Do not use normalized Euclidean distance.objMaxMin = ones(1,numObj);
else% 3) Errorerror('NSGA2:ParamError', ...'No support parameter: options.refUseNormDistance="%s", only "yes" or "no" are supported',...opt.refUseNormDistance);
end%*************************************************************************
% 2. Calculate preference distance pop(:).prefDistance
%*************************************************************************
for fid = 1:length(front)% Step1: Calculate the weighted Euclidean distance in each frontidxFront = front(fid).f;            % idxFront : index of individuals in current frontnumInd = length(idxFront);          % numInd : number of individuals in current frontpopFront = pop(idxFront);           % popFront : individuals in front fidobjFront = vertcat(popFront.obj);   % objFront : the whole objectives of all individualsif(bUseFrontMaxMin)objMaxMin = max(objFront) - min(objFront); % objMaxMin : the normalized factor in current frontend% normDistance : weighted normalized Euclidean distancenormDistance = calcWeightNormDistance(objFront, refPoints, objMaxMin, refWeight);% Step2: Assigned preference distanceprefDistanceMat = zeros(numInd, numRefPoint);for ipt = 1:numRefPoint[~,ix] = sort(normDistance(:, ipt));%升序排序,选择距离小的prefDistanceMat(ix, ipt) = 1:numInd;%排序位置endprefDistance = min(prefDistanceMat, [], 2); % 2表示计算每行min 对于参考点距离的rank位置,rank的值当作参考距离clear ix% Step3: Epsilon clearing strategyidxRemain = 1:numInd;           % idxRemain : index of individuals which were not processedwhile(~isempty(idxRemain))% 1. Select one individual from remainsobjRemain = objFront( idxRemain, :);selIdx = randi( [1,length(idxRemain)] );selObj = objRemain(selIdx, :);% 2. Calc normalized Euclidean distance% distanceToSel : normalized Euclidean distance to the selected pointsdistanceToSel = calcWeightNormDistance(objRemain, selObj, objMaxMin, refWeight);% 3. Process the individuals within a epsilon-neighborhoodidx = find( distanceToSel <= epsilon );     % idx : index in idxRemainif(length(idx) == 1)    % the only individual is the selected oneidxRemain(selIdx)=[];elsefor i=1:length(idx)if( idx(i)~=selIdx )idInIdxRemain = idx(i);     % idx is the index in idxRemain vectorid = idxRemain(idInIdxRemain);% *Increase the preference distance to discourage the individuals% to remain in the selection.prefDistance(id) = prefDistance(id) + round(numInd/2);endendidxRemain(idx) = [];endend% Save the preference distancefor i=1:numIndid = idxFront(i);pop(id).prefDistance = prefDistance(i);end

结构体定义之间要留空行

% pop : current population
% newpop : new population created by genetic algorithm operators
% combinepop = pop + newpop;
pop = repmat( struct(...'var', zeros(1,nVar), ...   % 变量值'obj', zeros(1,nObj), ...  %目标函数值'cons', zeros(1,nCons),...  % 'rank', 0,...'distance', 0,...'prefDistance', 0,...       % preference distance used in R-NSGA-II'nViol', 0,...   % The number of constraints 'violSum', 0),... % The sum of abs(constraints)[1,popsize]);  %struct 默认是行形式存在的,如果[2, popsize]则与数组相同% state: optimization state of one generation
state = struct(...
'currentGen', 1,...         % current generation number
'evaluateCount', 0,...      % number of objective function evaluation
'totalTime', 0,...          % total time from the beginning
'firstFrontCount', 0,...    % individual number of first front
'frontCount', 0,...         % number of front
'avgEvalTime', 0 ...        % average evaluation time of objective function (current generation)
);

函数定义体之间要留空行

函数体内,完整的控制结构和单独的语句块之间要留空行

GreyWolves=CreateEmptyParticle(GreyWolves_num);for i=1:GreyWolves_numGreyWolves(i).Velocity=0;GreyWolves(i).Position=zeros(1,nVar);for j=1:nVarGreyWolves(i).Position(1,j)=unifrnd(lb(j),ub(j),1);endGreyWolves(i).Cost=fobj(GreyWolves(i).Position')';GreyWolves(i).Best.Position=GreyWolves(i).Position;GreyWolves(i).Best.Cost=GreyWolves(i).Cost;
endGreyWolves=DetermineDomination(GreyWolves);
     % Eq.(3.4) in the paperc=2.*rand(1, nVar);% Eq.(3.1) in the paperD=abs(c.*Beta.Position-GreyWolves(i).Position);% Eq.(3.3) in the paperA=2.*a.*rand()-a;% Eq.(3.9) in the paperX2=Beta.Position-A.*abs(D);% Eq.(3.4) in the paperc=2.*rand(1, nVar);% Eq.(3.1) in the paperD=abs(c.*Alpha.Position-GreyWolves(i).Position);% Eq.(3.3) in the paperA=2.*a.*rand()-a;% Eq.(3.10) in the paperX3=Alpha.Position-A.*abs(D);

逻辑上密切相关的语句序列之间不要留空行

未完,待续!

Matlab代码书写规范相关推荐

  1. c#书写规范之---代码书写规范

    代码书写规范          格式化使代码的逻辑结构很明显.花时间确保源代码以一致的逻辑方式进行格式化,这对于您和你的开发小组,以及以后维护源代码的其他开发人员都有很大的帮助. 以下几点是推荐的格式 ...

  2. java 代码书写规范_代码书写规范和命名规范

    上一篇给大家分享了一下,关于文档编写的几个概念.这篇文章阐述如果编写代码书写规范以及命名规范文档.[以java语言为例] 1.代码书写规范 代码书写规范,能够让不同的人,写出相同风格的代码.很多人都看 ...

  3. GNU的C++代码书写规范,C语言之父Dennis Ritchie亲自修订 (转)

    GNU的C++代码书写规范,C语言之父Dennis Ritchie亲自修订 (转)[@more@]C++ Standard Library Style Guidelines  DRAFT 1999-0 ...

  4. GNU的C++代码书写规范

    GNU的C++代码书写规范,C语言之父Dennis Ritchie亲自修订 C++ Standard Library Style Guidelines  DRAFT 1999-02-26 ------ ...

  5. 网页编程代码书写规范

    网页编程,也就是网页代码的编写,其实也就是编程代码的书写,一个好的网站,其网页编码,是比较规范的,条理清晰,格式简洁美观,可读性强,那到底怎样才能规范好代码的编写规范,是一个值得大家深思的问题,想想自 ...

  6. 天勤考研中数据结构的代码书写规范以及C与C++语言基础

    考研综合应用题中算法设计部分的代码书写规范 头文件 头文件部分如果题目没有特殊说明可以去掉. 常量 如果题目中要用到一个常量,则在用的地方加上一句注释,说明某某常量已定义即可,不必在前面补上#defi ...

  7. C++代码书写规范简介

    C++代码书写规范简介 编码规范并不是必须的,写代码遵守一定的规范,会使阅读代码修改bug轻松一些. 作为代码初学者,了解掌握最基本的代码书写规范知识是必要的.由于代码不仅仅是让程序执行,代码更是给人 ...

  8. WEB前端代码书写规范

    WEB前端代码书写规范 1. 命名规范 a.ClassName命名 ClassName的命名应该尽量精短.明确,必须以单页面字母开头命名,且全部字母为小写,单词之间统一使用下划线 "_&qu ...

  9. Unity项目代码书写规范

    以Google的代码规范为主,稍加改动 https://google.github.io/styleguide/csharp-style.html 书写规范 基础写法 Pascal和驼峰混用,参数用驼 ...

最新文章

  1. uncompressing linux .................................................后没反应解决办法
  2. 5G时代,会有什么奇葩事儿?
  3. linux c调用wcf服务,Silverlight+WCF实现跨域调用
  4. Huggingface BERT源码详解:应用模型与训练优化
  5. c语言编写经验逐步积累3
  6. JSP文件如何转换成Java文件?
  7. package.json说明
  8. 卷积神经网络CNN介绍:结构框架,源码理解【转】
  9. 数据库完整性概念和数据库安全性概念之间的区别与联系
  10. golang websocket 聊天室demo
  11. java递归删除文件夹_如何使用递归删除Java中的目录/文件夹
  12. 谁说前端程序员不了解业务?站出来!
  13. MQTT 客户端工具
  14. 大众点评字体_大众点评字体解析
  15. JavaScript 模板引擎
  16. linux驱动开发(三):Linux字符设备驱动实例
  17. CSS,font-family,好看,常用,中文,字体(更新中)
  18. 邮件:TO, CC, BCC(收件人、抄送、密送)
  19. 视频是新时代的文本,微信也不得不认了!
  20. office 2016错误代码30175-13(30) win10

热门文章

  1. 朋友圈/评论/点赞/搜索/购物车
  2. sql简介香气和sql简介_香气和SQL简介
  3. 【C/C++学习笔记】C++11 random 随机数(TR1)
  4. 李宏毅2023春季机器学习笔记 - 01生成AI(ChatGPT)
  5. 【BZOJ 2054】 疯狂的馒头
  6. 写在清明(2007年)
  7. 基于字的二元模型拼音输入
  8. 云服务和传统服务器相比有哪些明显的优势
  9. 《SpringBoot2.0 实战》系列-整合FlyingSaucer + thymeleaf 实现模板文件转pdf打印
  10. nginx_centos