常用的MATLAB语法示例

文章来源小温Learning

下面提供学习这本书最常用的MATLAB语法示例。

A.1 表达式

x = 2^(2 * 3) / 4;
x = A \ b; % 解线性方程组的解
a == 0 & b < 0 % a等于0且b小于0
a ~= 4 | b > 0 % a不等于4或b大于0

A.2 函数m-files

function y = f(x) % 保存为 f.m
% 用来提供帮助的注释

function [out1, out2] = plonk(in1, in2, in3) % 保存为 plonk.m
% 三个输入参数,两个输出参数
...

function junk % 没有输入/输出参数;保存为 junk.m
[t, x] = ode45(@lorenz, [0 10], x0); % 使用函数句柄 @lorenz

A.3 图形

plot(x, y), grid % 在网格上绘制矢量y相对于x的图像
plot(x, y, 'b--'% 绘制蓝色虚线
plot(x, y, 'go'% 绘制绿色圆圈
plot(y) % 如果y是一个向量,则将元素相对于行号进行绘制
% 如果y是一个矩阵,则将列相对于行号进行绘制


plot(x1, y1, x2, y2) %该函数将 y1 相对于 x1 和 y2 相对于 x2 绘制在同一张图上。
semilogy(x, y) %该函数将 y 相对于 x 绘制在一个以 10 为底的对数刻度上。
polar(theta, r)%该函数生成一个极坐标图,其中 theta 是角度,r 是距离。

A.4 if 和 switch

if condition
    statement; % 当条件为真时执行
end;

if condition
    statement1; % 当条件为真时执行
else
    statement2; % 当条件为假时执行
end;

if a == 0 % 测试是否相等
    x = -c / b;
else
    x = -b / (2*a);
end;

if condition1 % 在第一个为真的条件处跳出
    statement1;
elseif condition2 % elseif 是一个单词!
    statement2;
elseif condition3
    statement3;
...
else
    statementE;
end;

if condition
    statement1;
else
    statement2;
end% 命令行

switch lower(expr) % expr是字符串或标量
    case {'linear','bilinear'}
        disp('Method is linear');
    case 'cubic'
        disp('Method is cubic');
    case 'nearest'
        disp('Method is nearest');
    otherwise
        disp('Unknown method.');
end;

A.5 for 和 while

for i = 1:n % 重复语句 n 次
    statements
end;

for i = 1:3:8 % i 取值为 1, 4, 7
    ...
end;

for i = 5:-2:0 % i 取值为 5, 3, 1
    ...
end;

for i = v % 索引 i 取每个向量 v 的元素
    statements
end;

for v = a % 索引 v 取矩阵 a 的每列
    statements
end;

for i = 1:n, statements, end % 命令行版本

try
    statements
catch
    statements
end

while condition % 当条件为真时重复语句

A.6 输入/输出

disp( x )

disp( ’Hello there’ )

disp([a b]) % two scalars on one line

disp([x’ y’]) % two columns (vectors x and y
must be same length)

disp( [’The answer is ’, num2str(x)] )

fprintf( ’\n’ ) % new line

fprintf( ’%5.1f\n’, 1.23 ) % **1.2

fprintf( ’%12.2e\n’, 0.123 ) % ***1.23e-001

fprintf( ’%4.0f and %7.2f\n’, 12.34, -5.6789 )
% **12 and **-5.68

fprintf( ’Answers are: %g %g\n’, x, y )
% matlab decides on format

fprintf( ’%10s\n’, str ) % left-justified string

x = input( ’Enter value of x: ’ )

name = input( ’Enter your name without apostrophes: ’, ’s’ )

A.7 load/save

load filename % 从二进制文件 filename.mat 中检索所有变量
load x.dat % 从 ASCII 文件 x.dat 导入矩阵 x
save filename x y z % 将变量 x、y 和 z 保存在 filename.mat 中
save % 保存所有工作区变量在 matlab.mat 中
save filename x /ascii % 将变量 x 以 ASCII 格式保存在 filename 中

A.8 向量和矩阵

a(3,:)    %提取矩阵 `a` 的第三行。
a(:,2)    %提取矩阵 `a` 的第二列。
v(1:2:9)  %提取向量 `v` 中从 1 到 9 的每个第二个元素。
v([2 4 5]) = [ ]  %移除向量 `v` 中的第二、四和五个元素。
v(logical([0 1 0 1 0]))%仅提取向量 `v` 的第二和第四个元素。
v' %矩阵 `v` 的转置。

默认 最新
当前暂无评论,小编等你评论哦!
点赞 评论 收藏
关注