分支语句和编程设计
关系运算符
运算符 | 运算 |
---|---|
== | 等于 |
~= | 不等于 |
> | 大于 |
>= | 大于或等于 |
< | 小于 |
<= | 小于或等于 |
逻辑运算符
& | 逻辑与 |
---|---|
l | 逻辑非 |
xor | 逻辑与或 |
~ | 逻辑非 |
逻辑函数
函数 | 解释 |
---|---|
ischar(a) | a是字符数组则返回1,否则返回0 |
isempty(a) | a是空数组则返回1,否则返回0 |
isinf(a) | a是无穷大则返回1,否则返回0 |
isnan(a) | a不是一个数则返回1,否则返回0 |
isnumeric(a) | a是一个数值数组则返回1,否则返回0 |
if结构
if control_expr_1
block1
elseif control_expr_2
block2
else
block3
end
每个条件语句后紧跟的语句都需要缩进两个空格,以增强程序的可读性。且在matlab中的if语句的结尾需要有end来结束。end会自动匹配最近的if。在if语句的嵌套结构中if…end的数量要匹配一致,否则会报错。
switch结构
switch (switch_expr)
case case_expr_1,
block1
case case_expr_2,
block2
…
otherwise,
block3
end
若判断的参数是多个,则{case_expr_1,case_expr_2,…}
try/catch结构
try/catch结构是选择结构的一种特殊形式,用于捕捉报错,若果一个错误发生在这个结构的try语句块中,那么程序将会执行catch语句块,程序将不会中断。
基本形式:
try
try block
catch
catch block
end
附加的画图特性
应用axis命令/函数
命令 | 功能 |
---|---|
v=axis | 此函数将会返回一个4元素行向量[xmin xmax ymin ymax] ,期中xmin xmax ymin ymax 代表x,y轴的下上限 |
axis([xmin xmax ymin ymax]) | xmin xmax设定横轴的下限及上限,ymin ymax设定纵轴的下限及上限 |
axis equal | 将横轴纵轴的尺度比例设成相同值 |
axis square | 横轴及纵轴的比例是1:1 |
axis normal | 以预设值画纵轴及横轴 |
axis off | 将纵轴及横轴取消 |
axis on | 这个命令打开所有的轴标签,核对符号、背景 |
MATLAB命令是通过函数来实现的,MATLAB编译器无论什么时候遇到这个命令,它都能转化为相应的函数。它把命令直接当作函数来用,而不是命令语法。
例:axis on == axis(‘on’)
###只有带有字符参数的函数才能当作命令,带有数字参数的函数只能被当作函数
在同一坐标系内画出多个图像
hold on 命令
执行hold on命令后,所有的新的图像都会叠加在原来存在的图像。hold off命令可以恢复默认情况,用新的图像来代替原来的图像。
例:
x=-pi:pi/20:pi;
y1=sin(x);
y2=cos(x);
plot(x,y1,‘b-’);
hold on;
plot(x,y2,‘k–’);
hold off;
legend (‘sin x’,‘cos x’);
创建多个图像
figure(n) n代表图象数
子图像
subplot(m,n,p)
在当前窗口创建m×n个子图像,按m行,n列排列,并选择子图像p来接受当前的命令
对画线的增强控制
属性 | 说明 |
---|---|
LineWidth | 用来指定线的宽度 |
MarkerEdgeColor | 用来指定标识表面的颜色 |
MarkerFaceColor | 填充标识的颜色 |
MarkerSize | 指定标识的大小 |
*文本字符串的高级控制
文本的字体可以通过stream modifiers修改
最普通的stream modifier:
.\bf | 黑体 |
---|---|
.\it | 斜体 |
.\rm | 恢复正常字体 |
.\fontname | 字体的名字 |
.\fontsize | 字体的大小 |
._{xxx} | xxx作为某字符的上标 |
.^{xxx} | xxx作为某字符的下标 |
###一旦一个 stream modifier 插入一个文本字符串中,它持续发挥作用,直到这个字符串的结束或消失。如果一个 modifier 后在跟着一个{},只有{}中的文本起作用。
极坐标图象
polar(theta,r)
theta 代表一个弧度角数组
r 一个距离数组
例:
% Script file: microphone.m
% Purpose:
% This program plots the gain pattern of a cardioid
% microphone.
% Record of revisions:
% Date Programmer Description of change
% ==== ===============================
% 12/10/97 S. J. Chapman Original code
% Define variables:
% g – Microphone gain constant
% gain – Gain as a function of angle
% theta – Angle from microphone axis (radians)
% Calculate gain versus angle
g = 0.5;
theta = 0:pi/20:2pi;
gain = 2g*(1+cos(theta));
% Plot gain
polar (theta,gain,‘r-’);
title (‘Gain versus angle \it\theta’);
#摘自《matlab编程》第82页