美文网首页
三、结构化程式与自定义函数

三、结构化程式与自定义函数

作者: 看远方的星 | 来源:发表于2021-06-27 11:16 被阅读0次

    1、Script writing
    2、Structured programming
    3、User-defined function

    1、Script writing

    1.1 MATLAB Script
    • A file containing a series of MATLAB commands
    • Pretty much like a C/C++program
    • Scripts need to be saved to a <file>.m file before they can be run
    image.png image.png
    for i=1:10
        x=linspace(0,10,101);
        plot(x,sin(x+i));
        print(gcf,'-deps', strcat('plot',num2str(i),'.ps'));
    end
    

    结果:


    image.png

    debug:


    image.png
    image.png
    1.2 Script Flow
    • Typically scripts run from the first line to the last


      image.png
    • Structured programming techniques(subroutine,loop, condition,etc)are applied to make the program looks neat

    Flow Control:


    image.png

    Relational(Logical)Operators:


    image.png
    • if elseif else
    if condition1  # 条件
        statement1  # 动作
    elseif condition2
        statement2
    else
        statement3
    end
    

    例子:

    a = 3;
    if rem(a,2) == 0  # rem是求余数的函数
        disp('a is even')  # even偶数
    else
        disp('a is odd')  # odd奇数
    end
    
    • "elseif" and "else" are optional

    • switch

    switch expression
    case value1    
        statement1
    case value2
        statement2
    
    otherwise
        statement
    end
    

    例如:

    input_num = 1;
    switch input_num
        case -1
            disp('negative 1');
        case 0
            disp('zero');
        case 1
            disp('positive 1');
        otherwise
            disp('other value');
    end
    

    结果:

    >> M03
    positive 1
    
    • while
    while expression
          statement
    end
    

    例子:

    n = 1;
    while prod(1:n) < 1e100     % prod()各元素相乘   e100是10的100次方
        n = n + 1;
    end
    n
    

    结果:

    >> M03
    n =
        70
    
    Exercise

    Use while loop to calculate the summation of the series 1+2+3+...+999

    n = 1
    a=0
    while n<1000
        a = a + n
        n = n+1
    end
    a
    

    结果:

    a =
          499500
    

    相关文章

      网友评论

          本文标题:三、结构化程式与自定义函数

          本文链接:https://www.haomeiwen.com/subject/faotultx.html