打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Matlab Coding Standard编程规范

1     Introduction

When writing code, in most cases you are not only writing for the computer
to  understand  and  make  use  of  your  code,     but  people  as  well!   This,  of course,  includes  yourself.   Will  you  understand  your  code  a  month  after having written it. By writing clear and highly readable code you reduce the risk of introducing unwanted errors.  It is the aim of this coding standard to help you write such code.
    Note   that  when   solving   home   problems    involving  programming,      you should use Matlab,  and  you  should follow  the  code  standard  described be- low.  Programs that deviate significantly from the code standard will result in deduction of points  even if the code works as intended.

2     Naming practices

When  naming  a  variable  (or  structure,  method  global  constant  etc.)       you should  always  strive  to  use  a  meaningful name  that  clearly  describes  the purpose of the variable.    For example a good name for the variable used to store the number of individuals in a population is populationSizewhereas simply  naming  the  variable  n is  not  recommended.        Using  long  names  is perfectly  acceptable;  When  given  a  choice,  a  long  but  descriptive  variable name is to be preferred over a short name with unclear meaning.


2.1    Variables

For variable names, the first character  should be in lower  case. If the variable  name  consists  of  several  words,  all  words  except  the  first  should  begin  with  an  upper  case  letter,  and  all  other  letters  should  be  lower  case,


e.g.  aLocalVariable.  As stated  above, using meaningful names should always  have  higher  priority  than  using short  names  and  this  is  especially  so in the case of variables with a large scope.  However, variables with limited scope  can  have  short  names.     For  example,   a  variable  used  for  storing  a temporary value within an  if-then statement (containing  only a few lines
of code between if(...) and end) may very well be named tmpVal.  In the case of a real-valued variable simply naming the variable x sufices.

2.1.1    Iterator variables

Iterator variables should be named using i, j and k.  However, in the case of a loop consisting of many lines of code, a longer and more meaningful name should preferably be used and should be prefixed with either  i, j or k. As an example, consider the iGenerationiterator variable of the main loop in FunctionOptimization.m.

2.1.2    Abbreviations

Abbreviations in variable names (as well as in names for methods etc.)  are acceptable  in  the  case  of  very  common  abbreviations,  e.g.  max  and  html. Note that the upper and lower case rule above still applies, e.g. cthStudent not CTHStudent.

2.1.3    Prefixes

As noted above, when using a longer name for an iterator variable, the name should include a prefix such as  i.  Also, the same prefix should be used for indexing variables, e.g.  iBestIndividualin FunctionOptimization.m.  In the case of a variable storing an integer  quantity,  e.g. the number of genes in  a  chromosome,    the  name  of  that  variable  should  include  the  prefix  n,
i.e. nGenes (nrOfGenes, is also ok).

2.2    Functions

Functions should be named using upper case for the first character of  every word in the function name, i.e.  InitializePopulation.  Function parameters are named as variables.     While variables are often named using nouns,
function names should preferably include at least one verb, since a function is intended to perform some action.  The file name should match the function name.  For example, the file containing the function InitializePopulation should be named InitializePopulation.m.

 

2.3    Structs

A struct is named using upper case letters the for the first character of each word in the name, i.e. using the same standard as for function names.

2.4    Global variables and constants

A global variable (declared using the keyword global) should be named using only capital letters, and with   in between words, e.g. A GLOBAL VARIABLE. However, the use of global variables and constants should be kept to a minimum.

3     Code organization and layout

3.1    Whitespace and other layout topics

Use whitespace to group your code in order to make it more readable.  Use vertical  whitespace  (i.e.  blank  lines)  to  form  blocks  of  lines  of  code,  quite similar to paragraphs when writing normal text.  Note that the lines of code that  constitute  a block should be cohesive  (i.e.  the lines  of  code should be strongly related to each other) and the formation of the block should be logical.  As an example, study the file FunctionOptimization.m. Use horizon
tal whitespace (i.e. indentation) to group statements, such as if-then-else and for-loops.    Use two blank spaces for indentation, on the form given in the following example.

if (r < crossoverProbability)
  newIndividual = NewIndividualsByCrossover(population,i1,i2,nGenes);
  temporaryPopulation(i,:) = newIndividual(1,:);
  temporaryPopulation(i+1,:) = newIndividual(2,:);
else
  temporaryPopulation(i,:) = population(i1,:);
  temporaryPopulation(i+1,:) = population(i2,:);
end

    Note the use of the two temporary variables  i1 and  i2 in the example.
This is perfectly fine as the scope is small.  Furthermore, since these variables are used for indexing, they are prefixed with i.

3.2    Avoid complex statements

In order to improve readability and avoid errors in code, avoid writing statements that each perform many steps of computation.  For example, the code snippet

 result = (abs(timeSeries.Value(i) - (delta*avg + (1-delta)*gamma))^kappa)* ...
           weightLeft/ (1+exp(alphaLeft*(timeSeries.Value(i) - (delta*avg + ...
           (1-delta)*gamma)-betaLeft)))+weightRight/(1+exp(-alphaRight* ...
           (timeSeries.Value(i) - (delta*avg + (1-delta)*gamma)-betaRight)));

should be written using several statements and temporary variables

x = timeSeries.Value(i);
z = x - (delta*avg + (1-delta)*gamma);
wR = weightRight/(1+exp(-alphaRight*(z-betaRight)));
wL = weightLeft/(1+exp(alphaLeft*(z-betaLeft)));
w = wR+wL;
result = (abs(z)^kappa)*w;

3.3    Conditional expressions

Avoid complex conditional expressions spanning over several lines.  Instead, introduce temporary boolean variables.

if (not(location == BUNKER) && ((sustainedWinds == CATEGORY_2_SUSTAINED_WINDS)
    &&(centralPressure == CATEGORY_2_CENTRAL_PRESSURE)))
   ...
end

should instead be coded as

isCategory2Winds = (sustainedWinds == CATEGORY_2_SUSTAINED_WINDS);
isCategory2Pressure = (centralPressure == CATEGORY_2_CENTRAL_PRESSURE);
isCategor2Hurricane = (isCategory2Winds && isCategory2Pressure);
outsideBunker = not(location == BUNKER);
if (isCategory2Hurricane && outsideBunker)
   ...
end

4     Code optimization

Whenever  you  have  the  choice    between  (1)  clear  but  slower  code  or  (2) cryptic and perhaps faster code you should always choose the clear and more readable code.  Do not bother with trying to improve the performance of your code  by  vectorization.  However,  this  does  not  imply  that  you  should  not pay  attention  to  the speed performance of  your  code.    In  order to  improve the  speed  performance  of  loops  you  should,  for  example,  always  initialize vectors and matrices before the loop, i.e.

fitness = zeros(populationSize);
for i = 1:populationSize

 parameterValues = DecodeChromosome(population,i,range,nGenes);
   fitness(i) = 1.0/EvaluateIndividual(parameterValues);

 

命名应该能够反映它们的意义或者用途;

  变量名和参数名应当使用“名词”或者“形容词+名词”,用小写字母开头的单词组合而成

    例如:

    float  value;

    float  oldValue;

    float  newValue;

    BOOL flag;

    int  drawMode;

  类名和函数名应当使用“动词”或者“动词+名词”(动宾词组),用大写字母开头的单词组合而成

    例如:

    DrawBox();  // 全局函数

    class Node;  // 类名

    class LeafNode;    // 类名

    void  Draw(void);    // 函数名

    void  SetValue(int value);  // 函数名

  类的成员函数应当只使用“动词”,被省略掉的名词就是对象本身

    例如:

    Box->Draw();        // 类的成员函数

  常量全用大写的字母,用下划线分割单词。

    例如:

    const int MAX = 100;

    const int MAX_LENGTH = 100;

  静态变量加前缀s_(表示static)

    例如:

    static int s_initValue;  // 静态变量

  如果不得已需要全局变量,则使全局变量加前缀g_(表示global)。

    例如:

    int g_howManyPeople;   // 全局变量

    int g_howMuchMoney;  // 全局变量

  类的数据成员加前缀m_(表示member),这样可以避免数据成员与成员函数的参数同名

    例如:

    void Object::SetValue(int width, int height)

    {

    m_width = width;

    m_height = height;

    }

  为了防止某一软件库中的一些标识符和其它软件库中的冲突,可以为各种标识符加上能反映软件性质的前缀

    例如:

    三维图形标准OpenGL的所有库函数均以gl开头,所有常量(或宏定义)均以GL开头

  用正确的反义词组命名具有互斥意义的变量或相反动作的函数等

    例如:

    int      minValue;

    int      maxValue;

    int      SetValue(…);

    int      GetValue(…);

  尽量避免名字中出现数字编号,除非逻辑上的确需要编号

    例如:

    Value1,Value2等

  不要出现仅靠大小写区分的相似的标识符

    例如:

    int  x,  X;          // 变量x 与 X 容易混淆

    void foo(int x);      // 函数foo 与FOO容易混淆

    void FOO(float x);

  不要出现标识符完全相同的局部变量和全局变量


(3) 命名中的一些简写规则;

  几开头的3-4个字母

    例如:exp=expert expe=experience lux=luxury prosperous=pros

  首尾字母

    例如:yr=year tx=telex

  去掉元音

    例如:pls=please rcv=receive rgd=registered dmst=demonstration

  谐音法

    例如:u=you 8=ate 4=for 2=to


   ...

1、就像别的语言一样变量命的命名为小写字母开头,第二个单词大写开头;

2、全局变量、常熟全部大写,为了可读性,单词间用下划线;

3、函数的命名最好不要缩写,一般都小写,就如matlab自己函数定义一样,uigetfile等

4、与matlab编辑器的缩排一致,缩排使用四个空格;

5、空白空格的使用:在=、&、|前后加空格;逗号后面加空格;

6、块间,逻辑组语句间用一个空白隔开,而blocks间一般用三个空白行隔开;

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
2.2 函数I(Functions I)
C语言变量和函数命名规范(2)
第五章 C 函数与程序结构
[C++语法] 关键字typedef用法(转)
C语言中地址操作符&的使用
CPP函数基础知识详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服