基本操作
-
PS1('>> ')
:简化命令行
-
%
:注释,~=
:不等于,&&
:且,||
:或
-
a = 3
, a = 3;
:后者抑制屏幕显示
-
disp()
:打印
-
disp(sprintf('hello world %.2f' , pi))
:格式化字符串
-
format long
, format short
:控制输出长度
向量和矩阵
1. v = [1 2 3], v = [1; 2; 3]
2. v = 1:6, v = 1:0.1:2
3. A = [1 2; 3 4; 5 6]
4. ones(2,3), 2 * ones(2,3), zeros(1,3)
5. rand(3,3), randn(3,3)
6. hist(randn(1,10000)), hist(randn(1,10000),50)
7. eye(3)
8. help rand, help help
加载存储数据
1.size(A), size(A,1), size(A,2)
2.pwd
3.length()
4.cd, ls
5.load
6.who, whos:显示变量
7.clear, clc
8.save hello.mat v, save hello.txt v
9.A(3,2), A(2,:), A(:,2):索引方式
10.A = [A,[100;101;102]]
11.A(:):将矩阵用列向量列出
12.C = [A B], C = [A;B]
数据运算
1.A * C, A.* C(元素位运算)
2.log(), exp(), abs(), max()
3.A'
4.[val,ind] = max(a):获取变量值及其索引
5.find(a<3):找出bool为真的索引
6.magic(3):获取行、列以及对角全相等的方阵
7.[r,c] = find(A>=7):获取矩阵的行、列索引
8.sum(), prod(), ceil(), floor()
9.max(A,[],1), max(A,[],2):max()默认按列取最大值
10.max(A(:)):取出矩阵所有值的最大值
11.flipud():将矩阵上下交换
12.pinv():返回逆
绘图
1.plot(x,y)
2.xlabel(), ylabel(), legend(), title()
3.print -dpng 'name.png'
4.close, close all
5.figure() :打开新窗口绘图
6.subplot(1,2,1)
7.axis([0.5 1 -1 1]):设置横纵轴范围
8.clf:清除
9.imagesc(A), colorbar, colormap gray:可视化矩阵
控制命令
for i = 1:10,
v(i) = 2^i;
end;
i = 1
while i <= 5,
v(i) = 100;
i = i + 1;
end;
i = 1
while true,
v(i) = 999;
i = i+1;
if i == 6,
break;
end;
end;
v(1) = 2;
if v(1) == 1,
disp('this is one');
elseif v(1) == 2,
disp('this is two');
else
disp('not one or two');
end;
函数
function y = costFunction(x)
y = x ^ 2;
function [y1,y2] = costFunction(x)
y1 = x ^ 2;
y2 = x ^ 3;
1.addpath():添加环境变量
2.exit
理解向量化