命令行选项解析函数(C语言):getopt()、getopt_long()和getopt_long_only

getopt()与getopt_long()的使用简介 感性认识 getopt()与getopt_long()是专门处理命令行参数的两个函数,getopt()处理短参数,getopt_long()处理长参数。还不明白请看下面这张图: 解析 -t yiqi 就是这两个函数做的事,下面我们一起来看看究竟如何使用好这两个函数。还不明白的请看下图: 非常清楚,命令行参数由Command name,Option,Option argument以及Operands组成。 Command name不用多说,就是程序的名称。 操作对象Operands又称no. 阅读详情

转载:http://www.cnblogs.com/liwei0526vip/p/4873111.html

上午在看源码项目 webbench 时,刚开始就被一个似乎挺陌生函数 getopt_long() 给卡住了,说实话这函数没怎么见过,自然不知道这哥们是干什么的。于是乎百度了一番,原来是处理命令行选项参数的,的确,正规点的大型程序一般第一步就是处理命令行参数的,接着才是主干程序。在百度和 man 的帮助下,找到了具体使用方法和解释,二话不说赶紧学习一下,并总结出文档记录一下。

平时在写程序时常常需要对命令行参数进行处理,因为参数少,自己解析就可以搞定;如果命令行个数比较多时,如果按照顺序一个一个定义参数含义很容易造成混乱,而且如果程序只按顺序处理参数的话,一些“可选参数”的功能将很难实现,这个问题在 linux 中用 getopt 等函数可以优雅地解决。

一、查询linux命令手册:

#include<unistd.h>
#include<getopt.h>          /*所在头文件 */
int getopt(int argc, char * const argv[], const char *optstring);

int getopt_long(int argc, char * const argv[], const char *optstring,const struct option *longopts, int*longindex);

int getopt_long_only(int argc, char * const argv[],const char *optstring,                          const struct option *longopts, int*longindex);

extern char *optarg;         /*系统声明的全局变量 */
extern int optind, opterr, optopt;

先拿最简单的 getopt 函数开刀,getopt_long 只是前者的增强版,功能多点而已。

二、getopt函数

1、定义:

int getopt(int argc, char * const argv[], const char *optstring);

2、描述:

getopt是用来解析命令行选项参数的,但是只能解析短选项: -d 100,不能解析长选项:–prefix

3、参数:

argc:main()函数传递过来的参数的个数 argv:main()函数传递过来的参数的字符串指针数组
optstring:选项字符串,告知 getopt()可以处理哪个选项以及哪个选项需要参数

4、返回:

如果选项成功找到,返回选项字母;如果所有命令行选项都解析完毕,返回 -1;如果遇到选项字符不在 optstring 中,返回字符
‘?’;如果遇到丢失参数,那么返回值依赖于 optstring 中第一个字符,如果第一个字符是 ‘:’ 则返回’:’,否则返回’?’并提示出错误信息。

5、下边重点举例说明optstring的格式意义:

char*optstring = “ab:c::”;
单个字符a 表示选项a没有参数 格式:-a即可,不加参数
单字符加冒号b: 表示选项b有且必须加参数 格式:-b 100或-b100,但-b=100错
单字符加2冒号c:: 表示选项c的参数可以有,也可以无 格式:-c200,其它格式错误

上面这个 optstring在传入之后,getopt 函数将依次检查命令行是否指定了 -a, -b, -c(这需要多次调用 getopt函数,直到其返回-1),当检查到上面某一个参数被指定时,函数会返回被指定的参数名称(即该字母)

optarg —— 指向当前选项参数(如果有)的指针。
optind —— 再次调用 getopt() 时的下一个 argv指针的索引。
opterr ­—— 如果不希望getopt()打印出错信息,则只要将全域变量opterr设为0即可。

以上描述的并不生动,下边结合实例来理解:

6、实例:

#include<stdio.h>
#include<unistd.h>
#include<getopt.h>
int main(intargc, char *argv[])
{
    int opt;
    char *string = "a::b:c:d";
    while ((opt = getopt(argc, argv, string))!= -1)
    {  
        printf("opt = %c\t\t", opt);
        printf("optarg = %s\t\t",optarg);
        printf("optind = %d\t\t",optind);
        printf("argv[optind] = %s\n",argv[optind]);
    }  
}

编译上述程序并执行结果:

输入选项及参数正确的情况

dzlab:~/test/test#./opt -a100 -b 200 -c 300 -d
opt = a optarg= 100 optind = 2 argv[optind] = -b
opt = b optarg = 200 optind = 4 argv[optind] = -c
opt= c optarg = 300 optind = 6 argv[optind] = -d
opt = d optarg = (null) optind = 7 argv[optind] = (null)

或者这样的选项格式(注意区别):

dzlab:~/test/test#./opt -a100 -b200 -c300 -d
opt = a optarg = 100 optind = 2 argv[optind] = -b200
opt = b optarg = 200 optind = 3 argv[optind] = -c300
opt = c optarg = 300 optind = 4 argv[optind] = -d
opt = d optarg = (null) optind = 5 argv[optind] = (null)

选项a是可选参数,这里不带参数也是正确的

dzlab:~/test/test#./opt -a -b 200 -c 300 -d
opt = a optarg = (null) optind = 2 argv[optind] = -b
opt = b optarg = 200 optind = 4 argv[optind] = -c
opt = c optarg = 300 optind = 6 argv[optind] = -d
opt = d optarg = (null) optind = 7 argv[optind] = (null)

输入选项参数错误的情况

dzlab:~/test/test#./opt -a 100 -b 200 -c 300 -d
opt = a optarg = (null) optind = 2 argv[optind] = 100
opt = b optarg = 200 optind = 5 argv[optind] = -c
opt = c optarg = 300 optind = 7 argv[optind] = -d
opt = d optarg = (null) optind = 8 argv[optind] = (null)

导致解析错误,第一个 optarg = null,实际输入参数 100,由于格式不正确造成的(可选参数格式固定)

参数丢失,也会导致错误,c选项是必须有参数的,不加参数提示错误如下:

dzlab:~/test/test#./opt -a -b 200 -c
opt = a optarg = (null) optind = 2 argv[optind] = -b
opt = b optarg = 200 optind = 4 argv[optind] = -c
./opt: optionrequires an argument – ‘c’
opt = ? optarg = (null) optind = 5 argv[optind] = (null)

这种情况,optstring 中第一个字母不是’:’,如果在 optstring 中第一个字母加’:’,则最后丢失参数的那个选项 opt 返回的是’:’,不是’?’,并且没有提示错误信息,这里不再列出。

命令行选项未定义,-e选项未在optstring中定义,会报错:

dzlab:~/test/test#./opt -a -b 200 -e
opt = a optarg = (null) optind = 2 argv[optind] = -b
opt = b optarg = 200 optind = 4 argv[optind] = -e
./opt: invalidoption – ‘e’
opt = ? optarg = (null) optind = 5 argv[optind] = (null)

到这里应该已经把getopt函数的功能讲解清楚了吧,下边来说说 getopt_long 函数,getopt_long 函数包含了 getopt 函数的功能,并且还可以指定”长参数”(或者说长选项),与 getopt 函数对比,getopt_long 比其多了两个参数:

三、getopt_long函数

1、定义:

int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts,int *longindex);

2、描述:

包含 getopt 功能,增加了解析长选项的功能如:–prefix –help

3、参数:

longopts 指明了长参数的名称和属性 longindex
如果longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值

4、返回:

对于短选项,返回值同getopt函数;对于长选项,如果flag是NULL,返回val,否则返回0;对于错误情况返回值同getopt函数

5、struct option

struct option {
const char  *name;       /* 参数名称 */
int          has_arg;    /* 指明是否带有参数 */
int          *flag;      /* flag=NULL时,返回value;不为空时,*flag=val,返回0 */
int          val;        /* 用于指定函数找到选项的返回值或flag非空时指定*flag的值 */
}; 

6、参数说明:

has_arg 指明是否带参数值,其数值可选:
no_argument 表明长选项不带参数,如:–name, –help
required_argument 表明长选项必须带参数,如:–prefix /root或 –prefix=/root
optional_argument 表明长选项的参数是可选的,如:–help或 –prefix=/root,其它都是错误

接着看一下实例操作会更加深刻地理解:

7、实例:

int main(intargc, char *argv[])
{
    int opt;
    int digit_optind = 0;
    int option_index = 0;
    char *string = "a::b:c:d";
    static struct option long_options[] =
    {  
        {"reqarg", required_argument,NULL, 'r'},
        {"optarg", optional_argument,NULL, 'o'},
        {"noarg",  no_argument,         NULL,'n'},
        {NULL,     0,                      NULL, 0},
    }; 
    while((opt =getopt_long_only(argc,argv,string,long_options,&option_index))!= -1)
    {  
        printf("opt = %c\t\t", opt);
        printf("optarg = %s\t\t",optarg);
        printf("optind = %d\t\t",optind);
        printf("argv[optind] =%s\t\t", argv[optind]);
        printf("option_index = %d\n",option_index);
    }  
}

编译上述程序并执行结果:

正确输入长选项的情况

dzlab:~/test/test#./long –reqarg 100 –optarg=200 –noarg
opt = r optarg =100 optind = 3 argv[optind] = –optarg=200 option_index = 0
opt = o optarg =200 optind = 4 argv[optind] = –noarg option_index = 1
opt = n optarg =(null) optind = 5 argv[optind] =(null) option_index = 2

或者这种方式:

dzlab:~/test/test#./long –reqarg=100 –optarg=200 –noarg
opt = r optarg =100 optind = 2 argv[optind] = –optarg=200 option_index = 0
opt = o optarg =200 optind = 3 argv[optind] = –noarg option_index = 1
opt = n optarg =(null) optind = 4 argv[optind] =(null) option_index = 2

可选选项可以不给参数

dzlab:~/test/test#./long –reqarg 100 –optarg –noarg
opt = r optarg =100 optind = 3 argv[optind] = –optarg option_index = 0
opt = o optarg =(null) optind = 4 argv[optind] =–noarg option_index = 1
opt = n optarg =(null) optind = 5 argv[optind] =(null) option_index = 2

输入长选项错误的情况

dzlab:~/test/test#./long –reqarg 100 –optarg 200 –noarg
opt = r optarg =100 optind = 3 argv[optind] = –optarg option_index= 0
opt = o optarg =(null) optind = 4 argv[optind] =200 option_index = 1
opt = n optarg =(null) optind = 6 argv[optind] =(null) option_index = 2

这时,虽然没有报错,但是第二项中 optarg 参数没有正确解析出来(格式应该是 —optarg=200)

必须指定参数的选项,如果不给参数,同样解析错误如下:

dzlab:~/test/test#./long –reqarg –optarg=200 –noarg
opt = r optarg =–optarg=200 optind = 3 argv[optind] =–noarg option_index = 0
opt = n optarg =(null) optind = 4 argv[optind] =(null) option_index = 2

长选项的举例说明暂且就这么多吧,其它如选项错误、缺参数、格式不正确的情况自己再试验一下。

四、getopt_long_only函数

getopt_long_only 函数与 getopt_long 函数使用相同的参数表,在功能上基本一致,只是 getopt_long 只将 –name 当作长参数,但 getopt_long_only 会将 –name 和 -name 两种选项都当作长参数来匹配。getopt_long_only 如果选项 -name 不能在 longopts 中匹配,但能匹配一个短选项,它就会解析为短选项。

C语言处理参数的 getopt() 函数 getopt() 函数用于解析命令行参数。它的 argc 和 argv 参数通常直接从 main() 的参数直接传递而来。optstring 是可以处理选项字母组成的字符串。该字串里的每个字符对应于一个以 ‘-’ 开头的选项。如果该字串里的任一字符后面有冒号,那么这个选项就要求有参数(如“hd:”对应于 '-h' 和 '-d', 其中 '-d' 后需接参数)。而如果选项后面接两个冒号,则说明这个选项后的参数是可选的,即可带参数也可不带参数。 阅读详情

相关推荐

getopt, getopt_long, getopt_long_only

命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"--"。如:-a,-A,-b都表示短选项;--all,--almost-all,--author都表示长选项。getopt_long_only类似于getopt_long,但是'-'和"--"都可以表示长选项。如果以'-'(不是"--")开头的选项不匹配长选项,但匹配短选项,则将其解析为短选项。getopt_long函数的工作原理与getopt类似,只是它也接受以两个短划线开头的长选项。

数字人生 558

linux系统getopt函数详解

getopt()函数就是用来解析命令行参数 调用形式一般如下: while((c = getopt(argc, argv, "xy:z::")) != -1){       switch(c){       case 'x':   ... ...       case 'y':   ... ...       case 'z':   ..

wangpengqi的专栏 1万+

SAP CO-PA获利分析避坑指南:从数据采集到报表设计的5个关键步骤

本文深入解析了SAP CO-PA获利分析模块从数据采集到报表设计的完整流程。文章重点剖析了数据源头、特征派生、获利段设计等关键步骤,并对比了基于账户与基于成本核算两种模式的差异,特别强调了在S/4HANA时代的选择与常见陷阱,旨在帮助企业构建可靠、可执行的盈利分析体系。

flink9streamer的博客 826

函数getopt_long_only()

第一次接触这个函数,是因为学习mjpg-streamer的源码。 函数作用:对命令行选项进行解析。函数出处 头文件getopt.h中:#include <getopt.h> int getopt_long_only(int argc, char * const argv[], const char *optstring, con

心系欣 1345

避坑指南:从聚宽迁移到QMT必须知道的5个细节(含Redis连接异常处理)

本文详细解析了从聚宽迁移到QMT平台时需注意的5个关键细节,特别是Redis连接池优化和xtquant重连机制。通过实战代码示例,帮助量化团队解决信号传递稳定性、时间同步、滑点控制等核心问题,确保交易策略平稳过渡。

weixin_27303545的博客 428

电流模架构Bandgap设计与仿真

带隙基准作为集成电路中一个重要模块,被广泛应用在低压差线性稳压(LDO)、充电电池保护芯片和通信电路、射频收发器、flash存储器等多种模拟及数模混合集成电路中,并且是片上集成系统(SOC)芯片中不可或缺的部分,为整个芯片提供精确的电压参考点............

qq_50968231的博客 5万+

Linux 命令行解析函数getopt()、getopt_long()、getopt_long_only()详解

Linux 命令行解析函数 概述 Linux是基于命令行的,而这些命令通常又带有各种参数,这样一来就需要提供一些机制或者说是函数去接口去处理这些命令行参数。 getopt()、getopt_long()、getopt_long_only()函数是GNU C提供的用来解析命令参数的一个库函数。下面来详细介绍一下getopt_long函数。 getopt()只能用来处理短选项,而getlo...

wit_732的博客 1145

从零开始用STM32驱动RGB屏:配置PCLK、DE同步信号的避坑指南

本文详细介绍了如何使用STM32驱动RGB接口LCD屏幕,重点解析了PCLK配置、同步信号极性和DE使能等关键参数的设置方法。通过实战代码示例和常见问题排查指南,帮助开发者避免常见配置错误,实现稳定的显示效果。特别针对800x480 IPS屏提供了优化建议和调试技巧。

sky77的博客 540

深入理解 getopt_long,getopt_long_only

getopt_long, getopt_long_only – 命令行解析函数,支持长选项解析 【说明】 getopt_long/getopt_long_only 是 getopt 的泛集,getopt 是 getopt_long 的一个子集,getopt 支持的所有特性,getopt_long 都支持,包括错误打印、argv 元素顺序调整等;getopt_long 相比 getopt 增加了长选...

amei113的专栏 1810

TMC5160电机驱动芯片实战:从模式选择到参数配置全解析

本文深入解析TMC5160电机驱动芯片的实战应用,涵盖三种核心工作模式的选择策略与参数配置。详细介绍了全功能运动控制、外部脉冲驱动及独立驱动模式的应用场景与配置要点,并提供了电流控制、静音优化、SPI通信及高级功能(如StallGuard2)的调优指南,帮助开发者充分发挥其高精度、低噪音性能。

weixin_29179311的博客 323

飞牛NAS+Docker打造私人IPTV直播源:手把手教你部署iptv-api

本文详细介绍了如何在飞牛NAS上通过Docker部署iptv-api,打造私人IPTV直播源。从SSH配置到Docker容器部署,手把手教你实现自动更新直播源、多终端支持的解决方案,适用于Kodi、PotPlayer等播放器,提升家庭娱乐体验。

earth的博客 5577

浅谈linux的命令行解析参数之getopt_long函数

前言         在linux中,经常需要各种命令,通常情况下都会带各种参数,而这些参数是如何解析的呢?通常使用GNU C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数。一、关于命令行参数     命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"--",如下表(ls 命令参数)所示,...

爱拼才会赢 7万+

音频DSP开发中的‘隐藏关卡’:那些SigmaStudio未公开的模块计算秘籍

本文深入探讨音频DSP开发中SigmaStudio未公开的模块计算秘籍,重点解析动态范围控制、均衡器参数映射和混响算法优化等核心模块计算公式。通过实际案例揭示如何利用这些非官方技巧提升音频质量与系统性能,为ADI DSP开发者提供宝贵的实战经验。

water的专栏 911

C语言linux getopt_long()函数(命令行解析)(getopt、getopt_long_only)(短选项 -,长选项 --)(option结构体)(optind、optarg变量)

参考文章:浅谈linux的命令行解析参数之getopt_long函数 文章目录前言一、关于命令行参数二、getopt_long函数参数以及返回值介绍(以上三个函数都适用):1、argc和argv和main函数的两个参数一致。2、optstring: 表示短选项字符串。3、longopts:表示长选项结构体。结构如下:4、longindex:longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值。5、全局变量:6、返回值:三、测试(自行测试

Dontla的博客 1万+

5个必知的脑网络图论指标:从聚类系数到小世界特性(附BCT工具包使用指南)

本文深度解析脑网络图论分析中五个核心指标:聚类系数、特征路径长度、全局效率、局部效率及节点效率,并详解其计算与解读。结合Brain Connectivity Toolbox工具包,提供从实战计算、常见报错解决到小世界特性统计检验的完整指南,帮助研究者跨越理论与实操鸿沟,让连接矩阵数据真正服务于神经科学研究。

blue42的博客 925

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

getopt 和 getopt_long 命令行解析函数

getopt 和 getopt_long 命令行解析函数

hinewcc的博客 4006

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

getopt和getopt_long函数

平时在写程序时常常需要对命令行参数进行处理,当命令行参数个数较多时,如果按照顺序一个一个定义参数含义很容易造成混乱,而且如果程序只按顺序处理参数的话,一些“可选参数”的功能将很难实现。 在Linux中,我们可以使用getopt、getopt_long、getopt_long_only来对这个问题进行处理。 #include int getopt(int ar

Cashey1991的专栏 5万+

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C语言中getopt()函数的用法

1.getopt()函数 getopt函数用来解析命令行选项,声明所在头文件为: #include <unistd.h> 函数原型如下: int getopt(int argc, char * const argv[], const char *optstring); 第一个参数argc是

Mculover666的博客(嵌入式) 1万+

getopt.h和getopt(),getopt_long()等函数

下载了一个牛人的代码,里面包括了一个getopt.h的头文件,在vs2008下无法通过编译,没有这个头文件,上网搜索了一些信息,记录下来,以方便以后查阅。      getopt.h和对应的链接库不是每个编译器都有的,gcc编译器好像是有的,但是在vs2008是没有的,所以就要去网上下载跨平台的代码,不管怎么样,最终要把getopt.h和相应的lib文件和工程链接起来,这样才不会报错。这些都比较

涛行无疆的专栏 1万+

命令行选项解析函数(C语言):getopt()和getopt_long()

命令行选项解析函数(C语言):getopt()和getopt_long() 上午在看源码项目webbench时,刚开始就被一个似乎挺陌生函数getopt_long()给卡住了,说实话这函数没怎么见过,自然不知道这哥们是干什么的。于是乎百度了一番,原来是处理命令行选项参数的,的确,正规点的大型程序一般第一步就是处理命令行参数的,接着才是主干程序。在百度和man的帮助下,找到了具体使用方法和解释,二

肖邦学习之路点滴 4384

【Linux函数】命令行参数解析函数

linux中命令行参数解析函数的用法

福州最帅男模的博客 2160

C语言:命令行选项解析函数---getopt()和getopt_long()

上午在看源码项目 webbench 时,刚开始就被一个似乎挺陌生函数 getopt_long() 给卡住了,说实话这函数没怎么见过,自然不知道这哥们是干什么的。于是乎百度了一番,原来是处理命令行选项参数的,的确,正规点的大型程序一般第一步就是处理命令行参数的,接着才是主干程序。在百度和 man 的帮助下,找到了具体使用方法和解释,二话不说赶紧学习一下,并总结出文档记录一下。 平时在写程序时常常需要...

houxiaoni01的博客 1325

C语言:命令行选项解析函数(C语言):getopt()和getopt_long()

  平时在写程序时常常需要对命令行参数进行处理,因为参数少,自己解析就可以搞定;如果命令行个数比较多时,如果按照顺序一个一个定义参数含义很容易造成混乱,而且如果程序只按顺序处理参数的话,一些“可选参数”的功能将很难实现,这个问题在 linux 中用 getopt 等函数可以优雅地解决。 一、查询linux命令手册: #include<unistd.h> #include<getopt.h> /*所在头文件 */ int getopt(intargc, char *

weixin_44498318的博客 771

getopt、getopt_long和getopt_long_only的用法

引子 前段时间博主曾写过一个Linux下的小项目叫myls,也就是实现了ls的基本功能。myls的命令行参数解析是由博主自己编码完成的,这可把博主给坑惨了!博主不久前查资料的时候看到了getopt、getopt_long和getopt_long_only这三个函数,发现这三个函数堪称命令行参数解析的“神器”!早知道有这样的工具,博主也不至于被命令行参数解析所困扰了。这么好的东西当然要分享给大家啦!所以博主写了这篇博客,也欢迎大佬指教! 用途 getopt、getopt_long和getopt_long_on

VincilLau的博客 881

getopt和getopt_long函数的参数解析

目录getopt()函数getopt_long()函数getopt_long_only() 函数   当在做嵌入式开发或网络编程时,通常会因为产品型号不同,或者监听的端口号不同需要对程序进行修改,因此为了提高代码重用性,我们可以在执行程序时出传入相应的命令行参数,减少对源码的修改。在linux 中有提供了三种函数可以对命令行参数进行处理:getopt()、getopt_long()、getopt_...

weixin_42647166的博客 970
上一篇: htonl htons ntohs ntohl的区别
nmglwy
博客等级 码龄15年 8粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值