
完整版教程下载地址:http://www.armbbs.cn/forum.php?mod=viewthread&tid=94547
本期教程主要是讲解Matlab的m文件简易使用方法,有些内容跟上一节相同,但是比上一些更详细。
4.1 初学者重要提示
4.2 Matlab的脚本文件.m的使用
4.3 Matlab中的条件和循环函数
4.4 绘图功能
4.5 总结
在matlab上创建和使用.m文件跟在MDK或者IAR上面创建和使用.C或者.ASM文件是一样的。创建方法如下:

点击上图中的小图标,打开编辑窗口后,输入以下函数:
r = rand(50,1);
plot(r)编辑好函数后需要将当前文件进行保存:

然后点击如下图标即可运行(或者按F5):

显示效果如下:

matlab也支持类似C语言中的条件和循环语句:for, while, if, switch。但在matlab中使用比在C中使用更加随意。
nsamples = 5;
npoints = 50;
for k = 1 : nsamples
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData);
end
overallMean = mean(sampleMean)在命令窗口得到输出结果:

nsamples = 5;
npoints = 50;
for k = 1:nsamples
iterationString = ['Iteration #',int2str(k)];
disp(iterationString) %注意这里没有分号,这样才能保证会在命令窗口输出结果
currentData = rand(npoints,1);
sampleMean(k) = mean(currentData) %注意这里没有分号
end
overallMean = mean(sampleMean) %注意这里没有分号在命令窗口得到输出结果:

if overallMean < .49
disp('Mean is less than expected')
elseif overallMean > .51
disp('Mean is greater than expected')
else
disp('Mean is within the expected range')
end命令窗口输出结果如下(这里仅列出了最后三行):

比如在命令窗口或者.m文件中写如下函数:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y, x,y2, x,y3)
legend('sin(x)','sin(x-.25)','sin(x-.5)')
plot(x, y, 'color_style_marker')
下面通过几个实例看一下实际显示效果。
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,'ks')显示效果如下:

下面函数的显示效果:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,'r:+')下面函数的显示效果如下:

默认情况下函数plot只绘制数据的实部,如果是下面这种形式,实部和虚部都会进行绘制。plot(Z)也就是plot(real(Z),imag(Z))。下面我们在命令窗口中实现如下函数功能:
t = 0:pi/10:2*pi;
plot(exp(i*t),'-o')
axis equal显示效果如下:

使用函数hold on即可实现,这个函数我们在上一章节中已经使用过,作用就是在当前绘图的基础上加上一个新的绘图。
% Obtain data from evaluating peaks function
[x,y,z] = peaks;
% Create pseudocolor plot
pcolor(x,y,z)
% Remove edge lines a smooth colors
shading interp
% Hold the current graph
hold on
% Add the contour graph to the pcolor graph
contour(x,y,z,20,'k')
% Return to default
hold off显示效果如下:

axis on %设置可见
axis off %设置不可见grid on %设置可见
grid off %设置不可见axis square %设置X,Y轴等长
axis equal %设置X,Y相同的递增。
axis auto normal %设置自动模式。axis([xmin xmax ymin ymax]) %二维
axis([xmin xmax ymin ymax zmin zmax]) %三维
axis auto %设置自动下面通过一个简单的实例说明一下图像数据的绘制,在命令窗口下操作即可。
>> load durer
>> whos
Name Size Bytes Class Attributes
X 648x509 2638656 double
ans 648x509 2638656 double
caption 2x28 112 char
map 128x3 3072 double
>> image(X) %显示图片
>>colormap(map) %上色
>> axis image %设置坐标
使用相同的方法,大家可以加载图片detail进行操作。另外用户可以使用函数imwrite和imread操作标准的JPEG,BMP,TIFF等类型的图片。
本期主要跟大家讲解了Matlab的简单使用方法,需要大家多查手册,多练习。