• Matlab2015基本语句语法04


    1. 输入、输出、格式化输出

    1) 读入数据:input

    >>number:   num=input('Give me your number: ');

    >>string:   str=input('Please enter a string: ', 's');

    2) 输出函数:disp

    >>输出单个值number, string均可   eg: disp('hello') disp(20.0)

    >>输出一个行向量vector        eg: disp(['I ', 'love ', 'my ', 'mom']);

    3) 格式化输出:fprintf         eg: fprintf('X is %4.2f meters ', 9.9);

    % disp 输出
    num=123;
    disp(num);
    str='my string';
    disp(str);
    
    disp(20.0);
    disp('is a string');
    
    disp(['I ', 'love ', 'my ', 'mom']);
    
    % num2str 数字转 字符串
    disp(['I ', 'am ', num2str(20)]);
    
    % fprintf 格式化输出
    fprintf('X is %4.2f meters
    ', 9.9);
    

      

    2. if语句

    % if 语句练习
    
    x=input('Give me your number: ');
    if x==1
        b=x.^2
    elseif x==2
        b=x.^x
    else
        b=0
    end
    

    3. switch-case语句  

    % input 与 switch 结合
    x = input('give me a number: ');
    
    switch x
        case 1
            y=10^1
        case 2
            y=10^2
        otherwise
            y=10^0
    end
    

    4. for循环语句

    1) 命令格式

         for  循环控制变量=变量范围

         语句组

         end

    注: 变量范围通常用向量表示

    % for 循环
    for a=10:20
        fprintf('value of a is %d 
    ', a);
    end
    
    for b=1.0:-0.1:0
        disp(b);
    end
    

      

    5. while循环语句

    1) 命令格式

      while  判断条件

        语句组

      end

    注: 判断条件同IF语句

    % while 循环
    a=1;
    while a<=10
        fprintf('value of a: %d
    ', a);
        a=a+1;      %ok
    %     a++;      %无效
    %     a+=1;    %无效
    end
    

      

    6. break语句

    作用: 结束循环,一般和if语句结合使用

    说明: 直接使用,只能退出当前一层循环;多层循环的情况后面补充

    b=1;
    while true
        fprintf('value of b: %d
    ', b);
        b=b+1;
        if b>10
            break;
        end
    end
    

      

    7. continue语句

    作用: 跳过后面的语句(结束这次循环),开始下一次的循环;

    % continue 语句使用: 结束本次循环,开始下一次循环
    c=1;
    while c<=10
        if c==5
            c=c+1;
            continue;
        end
        fprintf('value of c: %d 
    ', c);
        c=c+1;
    end
    

      

    8. 循环嵌套

    1) for 嵌套

    for i=x:y

      for j=m:n

         语句组

      end

    end

    2) while 嵌套

    while  条件

      while  条件

        语句组

      end

    end

    9. 自定义函数

    1) new Function(比new script更方便)

    function y = myFunction(x)
    % 直接编辑代码即可, 不用在额外缩进,如下格式
    y=2^x;
    end
    

      

     未完待续...

  • 相关阅读:
    07word转换pdf
    高德纳《计算机程序设计艺术》(The Art of Computer Programming)的作者
    DbVisualizer 8 解决中文乱码问题 (20120310 20:23)
    IT has never been easier or harder
    el表达式和s:property的区别
    df 和 du 命令详解
    dbvisualizer 8.0 破解(free>personal)
    ping 中的TTL查看操作系统
    netstat 监控TCP/IP网络
    ls l 命令
  • 原文地址:https://www.cnblogs.com/AbcFly/p/5994169.html
Copyright © 2020-2023  润新知