源作者:一块二毛三分钱
matlab运行程序后工作区空白编程和脚本
脚本是最简单的一种 MATLAB® 程序。脚本是一个包含多行连续 MATLAB 命令和函数调用的扩展名为.m
的文件。在命令行中键入脚本名称即可运行该脚本。
示例脚本
要创建脚本,请使用edit
命令。
edit plotrand
这会打开一个名为plotrand.m
的空白文件。输入一些绘制随机数据的向量的代码:
n = 50;
r = rand(n,1);
plot(r)
然后,添加在绘图中的均值处绘制一条水平线的代码:
m = mean(r);
hold onplot([0,n],[m,m])
hold offtitle('Mean of Random Uniform Data')
编写代码时,最好添加描述代码的注释。注释有助于其他人员理解您的代码,并且有助您在稍后返回代码时再度记起。使用百分比 (%
) 符号添加注释。
% Generate random data from a uniform distribution% and calculate the mean. Plot the data and the mean.
n = 50; % 50 data pointsr = rand(n,1);
plot(r)
% Draw a line from (0,m) to (n,m)m = mean(r);
hold onplot([0,n],[m,m])
hold offtitle('Mean of Random Uniform Data')
将文件保存在当前文件夹中。要运行脚本,请在命令行中键入脚本名称:
plotrand
还可以从编辑器通过按运行按钮
运行脚本。
循环及条件语句
在脚本中,可以使用关键字for
、while
、if
和switch
循环并有条件地执行代码段。
例如,创建一个名为calcmean.m
的脚本,该脚本使用for
循环来计算 5 个随机样本的均值和总均值。
nsamples = 5;
npoints = 50;for k = 1:nsamples
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData);endoverallMean = mean(sampleMean)
现在,修改for
循环,以便在每次迭代时查看结果。在命令行窗口中显示包含当前迭代次数的文本,并从sampleMean
的赋值中删除分号。
for k = 1:nsamples
iterationString = ['Iteration #',int2str(k)];
disp(iterationString)
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData)endoverallMean = mean(sampleMean)
运行脚本时,会显示中间结果,然后计算总均值。
calcmean
Iteration #1
sampleMean =
0.3988
Iteration #2
sampleMean =
0.3988 0.4950
Iteration #3
sampleMean =
0.3988 0.4950 0.5365
Iteration #4
sampleMean =
0.3988 0.4950 0.5365 0.4870
Iteration #5
sampleMean =
0.3988 0.4950 0.5365 0.4870 0.5501
overallMean =
0.4935
在编辑器中,在calcmean.m
末尾添加根据overallMean
的值显示不同消息的条件语句。
if overallMean.51
disp('Mean is greater than expected')else
disp('Mean is within the expected range')end
运行calcmean
并验证是否显示关于计算的overallMean
的正确消息。例如:
overallMean =
0.5178
Mean is greater than expected
脚本位置
MATLAB 在特定位置中查找脚本及其他文件。要运行脚本,该文件必须位于当前文件夹或搜索路径中的某个文件夹内。
默认情况下,MATLAB 安装程序创建的MATLAB
文件夹位于此搜索路径中。如果要将程序存储在其他文件夹,或者要运行其他文件夹中的程序,请将其添加到此搜索路径。在“当前文件夹”浏览器中选中相应的文件夹,右键点击,然后选择添加到路径。