-
腳本
程式控制結構
順序結構
>> 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