天天看点

Matlab基础——程序设计

  • 脚本

程序控制结构

顺序结构

>> a=input('a=?');
b=input('b=?');
c=input('c=?');
d=b*b-4*a*c;
x=[(-b+sqrt(d))/(2*a),(-b-sqrt(d))/(2*a)];
disp(['x1=',num2str(x(1)),'x2=',num2str(x(2))]);
a=?12
b=?15
c=?17
x1=-0.625+1.0129ix2=-0.625-1.0129i
           

选择结构

>>    %  计算分段函数
 x=input('请输入x的值:');
 if x==10
     y=cos(x+1)+sqrt(x*x+1);
 else
     y=x*sqrt(x+sqrt(x));
 end
 y
请输入x的值:5

y =

   13.4500
           
>> price=input('请输入商品价格');
 switch fix(price/100)    % fix()向0取整
     case{0,1}
         rate=0;
     case{2,3,4}
         rate=3/100;
     case num2cell(5:9)    % num2cell函数将数值矩阵转化为单位矩阵,价格大于500但小于1000
         rate=5/100;
     case num2cell(10:24)    % 价格大于1000小于2500
         rate=8/100;
     case num2cell(25:49)
         rate=10/100;
     otherwise
         rate=14/100;
 end 
 price=price*(1-rate)
请输入商品价格520

price =

   494
           
>>  A=[1 2 3;4 5 6];
 B=[7 8 9;10 11 12];
 try
     C=A*B;
 catch
     C=A.*B;
 end
 C 
 lasterr    % 显示出错原因

C =

     7    16    27
    40    55    72


ans =

    '错误使用  * 
     用于矩阵乘法的维度不正确。请检查并确保第一个矩阵中的列数与第二个矩阵中的行数匹配。要执行按元素相乘,请使用 '.*'。'
           

循环结构

>> y=0;n=100;
 for i=1:1:n
     y=y+1/i/i;
 end
 y

y =

    1.6350
           
>>  sum=0;
 n=0;
 x=input('Enter a number(end in 0):');
 while(x~=0)
     sum=sum+x;
     n=n+1;
     x=input('Enter a number(end in 0):');
 end
 if(n>0)
     sum
     mean=sum/n
 end
Enter a number(end in 0):5
Enter a number(end in 0):9
Enter a number(end in 0):0

sum =

    14


mean =

     7
           
  • 函数

function [s,p]=fcircle(r)
% FCIRCLE calculate the area and perimeter of a circle of radii r
% r 圆半径
% s 圆面积
% p 圆周长

%2018/8/21
s=pi*r*r;
p=2*pi*r;
           
>> [s,p]=fcircle(10)

s =

  314.1593


p =

   62.8319
           

继续阅读