- 0
- 0
- 约3.36千字
- 约 28页
- 2017-08-20 发布于浙江
- 举报
matlab_2013_教程_档内三章 选择语句
*;任何计算机语言都有三种基本结构:
?顺序结构:无控制语句
?分支结构:if , switch
?循环结构:for, while ;1、顺序结构:无控制语句;?分支结构:if , switch;格式1:if 表达式
语句
end;Fenzi = input(Please input enter the FENZI: );
Fenmu = input(Please input enter the FENMU: );
if(Fenmu == 0)
disp(Sorry The Fenmu can not be zero!);
else
fprintf(The result is %.2f.\n,Fenzi/Fenmu);
end;格式3:
if 表达式1
语句1
elseif 表达式2
语句2
else
语句3
end;2、switch语句(适合分支多) ;;例如:根据菜单选择显示不同的函数
x=menu(波形,正弦,余弦,正切,余切);
switch x
case 1
ezplot(sin)
case 2
ezplot(cos)
case 3
ezplot(tan)
case 4
ezplot(cot)
end ;menu函数 ;3、for语句 常用于计数循环;例: 已知 ,当n=100时,求y的值。
程序如下:
y=0;
n=100;
for i=1:n
y=y+1/(2*i-1);
end; 在实际MATLAB编程中,采用循环语句会降低其执行速度,所以前面的程序通常由下面的程序来代替:
n=100;
i=1:2:2*n-1;
y=sum(1./i);;for语句更一般的格式为:
for 循环变量=矩阵表达式
循环体语句
end
执行过程是依次将矩阵的各列元素赋给循环变量,然后执行循环体语句,直至各列元素处理完毕。; 例: 写出下列程序的执行结果。
s=0;
a=[12,13,14;15,16,17;18,19,20;21,22,23];
for k=a
s=s+k;
end
disp(s);;4、while 语句 常用于条件循环;clear;
x = input(Enter a maximum temp :);
while(x -16 || x 20)
x = input(Error! Enter a maximum temp :);
end;
i = 0;
fprintf(%6s%6s\n,F,C);
while(5/9*(i-32) x)
fprintf(%6.1f%6.1f\n,i,5/9*(i-32));
i = i + 5;
end;;fprintf函数可以将数据按指定格式写入到文本文件中。其调用格式为:
数据的格式化输出:fprintf(fid, format, variables)
按指定的格式将变量的值输出到屏幕或指定文件
fid为文件句柄,若缺省,则输出到屏幕;randn
产生均值为0,方差 σ^2 = 1,标准差σ = 1的正态分布的随机数或矩阵的函数。
用法:
Y = randn(n)
返回一个n*n的随机项的矩阵。如果n不是个数量,将返回错误信息。
Y = randn(m,n) 或 Y = randn([m n])
返回一个m*n的随机项矩阵。
Y = randn(m,n,p,...) 或 Y = randn([m n p...])
产生随机数组。
Y = randn(size(A))
返回一个和A有同样维数大小的随机数组。
randn
返回一个每次都变化的数量。
s = randn(state);rand
均匀分布的随机数或矩阵
用法:
Y = rand(n)
Y = rand(m,n)
Y = rand([m n])
Y = rand(m,n,p,...)
Y = rand([m n p...])
Y = rand(size(A))
rand
s = rand(state)
描述
rand函数产生由在(0, 1)之间均匀分布的随机数组成的数组
Y = rand(n) 返回一个n x n的随机矩阵如果n不是数量,则返回错误信息
Y = rand(m,n) 或 Y = rand([m n]) 返回一个m x n的随机矩阵
Y = rand(m,n,p,...)
原创力文档

文档评论(0)