• Matlab定义子函数


    上篇博客介绍了在Matlab中自己定义简单函数的方法,本篇博客将介绍定义子函数的方法。本文承接上篇博客的样例,即随机生成一个3行4列的矩阵,矩阵中的元素设定上下限为(low,high)。并返回矩阵全部元素的和。

    .m文件代码例如以下所看到的:

    function [a, s] = myRand(low, high)
    a = low + rand(3,4)*(high-low);
    v = a(:);
    s = sum(v);
    end



    如今,使用子函数实现上述函数的功能。代码例如以下所看到的:

    function [a, s] = myRand(low, high)
    a = low + rand(3,4)*(high-low);
    s = sumAllElement(a);
    
    function sum_a = sumAllElement(M)
    v = M(:);
    sum_a = sum(v); 
    上述代码定义了一个子函数sum_a。其被函数myRand所调用。须要注意的是,上述两个函数都没有以"end"keyword结尾。假设函数myRand以"end"keyword结尾,则子函数sum_a必须以"end"keyword结尾。反之亦然,否则会报错。

    在command window中运行myRand命令。得到的结果例如以下:

    >> [x ss] = myRand(2,4)
    x =
        2.9736    2.6127    3.6353    2.7572
        2.8717    3.0170    3.5897    3.6232
        2.8936    3.0215    3.2886    3.0657
    ss =
       37.3497



  • 相关阅读:
    libZPlay 音频编码解码器库
    C# PropertyGrid控件
    .netGDI+(转)
    (转)JITComplier、NGen.exe及.NET Native
    c# 特性/属性(Attribute) 以及使用反射查看自定义特性
    Fluent NHibernate系列文章
    Hibernate工作原理
    Orchard核心机制
    NHibernate和 FluentNHibernate
    极限编程之TDD
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5154527.html
Copyright © 2020-2023  润新知